2
int main() 
{
int n;
cin>>n;
string str1[n];
for(int i=0;i<n;i++)
    getline(cin,str1[i]);
return 0;
}

I wrote a code to input n strings but the code takes only (n-1) strings as input. What is the reason for this?

Robᵩ
  • 143,876
  • 16
  • 205
  • 276
Gibreel Abdullah
  • 285
  • 1
  • 2
  • 10
  • A related question provides the fix. The related question: http://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction. The fix: add `std::cin.ignore(std::numeric_limits::max(), '\n')` after `cin>>n;`. – Robᵩ Sep 17 '15 at 18:13
  • @Robᵩ thanks, solved my problem. – Gibreel Abdullah Sep 17 '15 at 18:19
  • 1
    [OT] `string str1[n];` is a variable length array and not standard. You can change it to `std::vector str1(n);` – NathanOliver Sep 17 '15 at 18:24
  • @NathanOliver - I'm new to this. Can you please explain `string str1[n];` should not be used. It works perfectly (after correcting the code that is) – Gibreel Abdullah Sep 18 '15 at 12:47
  • @GibreelAbdullah it is not standard, meaning the C++ standard does not included it in the features of C++. Some compilers like your allow it as a compiler extension since it is allowed in C99. The problem with using them in C++ is if you give someone else your code it might not compile as you are using something that isn't guaranteed to exist. IT is better to use a vector as vectors are part of the standard. – NathanOliver Sep 18 '15 at 12:54

1 Answers1

4

The for loop does run for n iterations, and getline does read in n lines. Consider this input:

2
First
Second

In that input there are three (not two!) lines: 2\n, First\n, and Second\n.

Your formatted input (cin>>n) reads part of the first line: 2. Then the loop runs twice, reading in this data: \n and First\n. The third and final line (Second\n) is never read.

The solution is to read the \n from the first line before the loop begins. This can be accomplished various ways. Here is one:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
Robᵩ
  • 143,876
  • 16
  • 205
  • 276