Omnimaga

General Discussion => Technology and Development => Computer Programming => Topic started by: Munchor on August 13, 2011, 06:15:18 am

Title: C++ GetLine for input
Post by: Munchor 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!
Title: Re: C++ GetLine for input
Post by: AHelper 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;
}
Title: Re: C++ GetLine for input
Post by: Munchor on August 13, 2011, 10:36:12 am
Thanks a lot AHelper, +1 ;)