Author Topic: C++ GetLine for input  (Read 7121 times)

0 Members and 1 Guest are viewing this topic.

Offline Munchor

  • LV13 Extreme Addict (Next: 9001)
  • *************
  • Posts: 6199
  • Rating: +295/-121
  • Code Recycler
    • View Profile
C++ GetLine for input
« on: August 13, 2011, 06:15:18 am »
I was tried to make a program that read X lines of input by the user and saved each line on a string.

However, if I tell it to get input 5 times, it only gets input 4 times.

Code: [Select]
#include <iostream>
#include <string>

using namespace std;

int main()
{
  int d, n, i;
  cin >> n;

  string line[n];
  for (i = 0; i < n; i++)
  {
    getline(cin, line[i]);
  }
 
  cout << endl;
 
  for (i = 0; i < n; i++)
  {
    cout << line[i] << endl;
  }
 
 
 
  return 0;
}

Basically, if I input "5" to the variable "n", it gets input 4 times, instead of 5.

What is the problem?

Thanks!

Offline AHelper

  • LV3 Member (Next: 100)
  • ***
  • Posts: 99
  • Rating: +18/-0
    • View Profile
    • GlaßOS razzl
Re: C++ GetLine for input
« Reply #1 on: August 13, 2011, 10:16:55 am »
Code: [Select]
#include <iostream>
#include <string>

using namespace std;

int main()
{
  int d, n, i;
  cin >> n;

  string line[n];
  // CHANGE: Ignore any characters still in the istream, such as the '\n' or any other non-int character
  cin.ignore();
  for (i = 0; i < n; i++)
  {
    getline(cin, line[i]);
  }
 
  cout << endl;
 
  for (i = 0; i < n; i++)
  {
    cout << line[i] << endl;
  }
 
 
 
  return 0;
}
SDCC tastes like air bags - big output, but fast and safe to run.

Offline Munchor

  • LV13 Extreme Addict (Next: 9001)
  • *************
  • Posts: 6199
  • Rating: +295/-121
  • Code Recycler
    • View Profile
Re: C++ GetLine for input
« Reply #2 on: August 13, 2011, 10:36:12 am »
Thanks a lot AHelper, +1 ;)