代码之家  ›  专栏  ›  技术社区  ›  user225312

std::getline和std::vector的怪异行为<std::string>

c++
  •  0
  • user225312  · 技术社区  · 15 年前

    我有以下代码:

    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
    

    但是,如果我的代码是:

    int tries = 3;         // explicitly specifying the number of tries
    int counter = 0;
    while(counter < tries) {}
    

    它按预期工作。为什么 std::cin >> tries 导致代码失败?

    3 回复  |  直到 15 年前
        1
  •  2
  •   Jerry Coffin    15 年前

    tries ,你按了回车键。你看了之后 ,回车键返回的回车仍在输入缓冲区中。该回车符通常会转换为新行字符。你的下一个电话 getline

        2
  •  1
  •   jdehaan    15 年前

    第一个条目的换行符仍在输入缓冲区中。

    std::cin.ignore(); 刚看完我的书 cin .

    这样新行就被丢弃了。

    我发现了一个很好的链接,它解释了很多关于I/O使用的事情:

        3
  •  0
  •   Oliver Charlesworth    15 年前

    你没有什么可以吸收的 '\n' 从你的第一行开始 std::cin >> tries .