...">

Why does getline skip the first line?

The following getline() code skips reading the first line. I noted that when commenting on the string " cin >> T " it works fine. But I can not understand the reason.

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

 #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; } 
+4
source share
3 answers
 cin >> T; 

This consumes the integer that you provide on stdin.

On the first call:

 getline(cin, line) 

... you are consuming a new line after an integer.

You can get cin in ignore new line by adding the next line after cin >> T;

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

(you will need #include <limits> for std::numeric_limits )

+8
source

Most likely, there is a new line in your input file, and it is processed immediately, as described on this page:

http://augustcouncil.com/~tgibson/tutorial/iotips.html

You can call cin.ignore() to reject one character, but you can read more tips as there are suggestions on how to handle reading in numbers.

+3
source

This line displays only a number:

 cin >> T; 

If you want to analyze user input, you need to consider that they continue to beat <enter> because the input is buffered. To get around this time, it is easier to read interactive input using getline. Then parse the contents of the string.

 std::string userInput; std::getline(std::cin, userInput); std::stringstream(userInput) >> T; 
+1
source

All Articles