Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why getline skips first line?

Tags:

c++

In the following code, getline() skips reading the first line. I noted that when commenting the "cin >> T" line, it works normally. But I can't figure out the reason.

I want to read an integer before reading lines! How to fix that?

#include <iostream>
using namespace std;

int main () {
    int T, i = 1;
    string line;

    cin >> T;

    while (i <= T) {
        getline(cin, line);
        cout << i << ": " << line << endl;
        i++;
    }

    return 0;
}
like image 960
Osama Gamal Avatar asked May 07 '11 00:05

Osama Gamal


1 Answers

cin >> T;

This consumes the integer you provide on stdin.

The first time you call:

getline(cin, line)

...you consume the newline after your integer.

You can get cin to ignore the newline by adding the following line after cin >> T;:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

(You'll need #include <limits> for std::numeric_limits)

like image 149
Johnsyweb Avatar answered Sep 21 '22 12:09

Johnsyweb