std :: getline和std :: vector< std :: string>的行为怪异 [英] Weird behaviour with std::getline and std::vector<std::string>
问题描述
我有以下代码:
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;
}
输入:
3
Here Goes
Here Goes 2
输出为:
<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) {}
它按预期工作.为什么 std :: cin>>尝试
导致代码失败?
It works as expected. Why is the std::cin >> tries
causing the code to fail?
我已经在VC ++ 2010和g ++ 4.4.3中对其进行了测试
I have tested it with VC++ 2010 and g++ 4.4.3
推荐答案
当您输入 tries
的数字时,您按了回车键.阅读 trys
后,按回车键返回的回车符仍位于输入缓冲区中.该回车符通常会转换为换行符.您对 getline
的下一次调用将读取输入缓冲区中的所有内容,直到下一行.由于第一个字符是换行符,因此将其读取为长度为零的行(即换行符之前为零个字符).
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).
这篇关于std :: getline和std :: vector< std :: string>的行为怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!