Reputation: 18181
I am trying to read the n-th line from the standard input in the following program. However, the console will print out "current line is" before I input any number...not sure what's wrong. Thanks for help.
int main()
{
string currentLine;
int n;
cin >> n;
cout << n << endl;
while (n > 0)
{
getline(cin, currentLine);
cout << "current line is" << currentLine << endl;
n--;
}
return 0;
}
Upvotes: 0
Views: 804
Reputation: 1510
In order to get n
, you have to input a number and press the Enter button. As @Kuhl said, the operator>>
stops as soon as its format can't be satisfied by the next character.
This means the first time getline(cin, currentline)
runs will get '\n' !
Then the program will output "current line is\n" while the '\n' will not be shown on the console.
If you want to get n
and 'currentline', you may choose the @Kuhl's answer or write the program like this:
getline(cin, currentline);
while(n>0) {
// anything you want
}
The getline(cin, currentline)
will help you to skip the '\n'
followed by the number 'n'.
Upvotes: 2
Reputation: 153840
The formatted input using operator>>()
stops as soon as its format can't be satisfied by the next character. For integers it stops when there is no further digit, e.g., when the next character is a whitespace like the newline from entering the line.
std::getline()
reads until it finds the first newline. There was one left right before when reading the integer. You probably want to extract this newline and potentially other whitespace. You could, e.g., use
if (std::getline(std::cin >> std::ws, currentLine)) {
// do something with the current line
}
else {
// deal with a failure to read another line
}
The manipulator std::ws
skips leading whitespace. As indicated above, you should also verify that the input was actually successful before processing input.
Upvotes: 3