Search code examples
c++stringgetline

getline() function in c++ takes 1 less input


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?


Solution

  • 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')