I have the following code:
std::vector<std::string> final_output;
std::string input;
int tries = 0;
std::cin >> tries;
int counter = 0;
while(counter < tries) {
std::getline(std::cin, input);
final_output.push_back(input);
++counter;
}
Given the input:
3
Here Goes
Here Goes 2
The output is:
<blank line>
Here Goes
Here Goes 2
Weirdly, it seems to enter a blank line as input for the first time it runs.
However, if I have the code as:
int tries = 3; 开发者_开发问答// explicitly specifying the number of tries
int counter = 0;
while(counter < tries) {}
It works as expected. Why is the std::cin >> tries
causing the code to fail?
I have tested it with VC++ 2010 and g++ 4.4.3
When you enter the number for tries
, you hit the return key. After you read tries
, the carriage return from hitting the return key is still sitting in the input buffer. That carriage return will normally be translated to a new-line character. Your next call to getline
reads everything in the input buffer up to the next new-line. Since the first character is a new-line, it reads that as a line of zero length (i.e., zero characters before the new-line).
The newline of the first entry is still in the input buffer.
You can call std::cin.ignore();
just after reading tries from cin
.
This way the newline gets discarded.
I found a good link that explains plenty of things regarding the use of I/O:
- http://www.augustcouncil.com/~tgibson/tutorial/iotips.html
You have nothing to absorb the '\n'
from the first line in your standalone std::cin >> tries
.
精彩评论