Weird behaviour with std::getline and std::vector<std::string>

匿名 (未验证) 提交于 2019-12-03 02:41:02

问题:

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

回答1:

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).



回答2:

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:



回答3:

You have nothing to absorb the '\n' from the first line in your standalone std::cin >> tries.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!