简体   繁体   English

在 std::getline 和 std::cin 在 while 循环期间陷入循环

[英]Stuck in loop during std::getline and std::cin during while loop

So I'm new to C++ and I'm supposed to get a vector in integers from stdin.所以我是 C++ 的新手,我应该从标准输入中得到一个整数向量。 I tried using std::cin and std::getline and other functions, but everytime I try entering a sentinel (eg not an integer) or when there is a "count" variable that reaches an increment, I end up in a hung state.我尝试使用 std::cin 和 std::getline 和其他函数,但是每次我尝试输入一个标记(例如,不是整数)或者当有一个“计数”变量达到增量时,我最终都会挂起 state . I can enter inputs, but no more print statements (eg "std::cout << "added") appear after the count has reached. I'm not sure what went wrong with the std::cin.我可以输入输入,但在达到计数后不再出现打印语句(例如“std::cout <<”add“)。我不确定 std::cin 出了什么问题。

std::vector<int> Game::getIds() {
    std::vector<int> cards; 
    int x =0 ;  
    std::string mystr; 
    bool keepGoing = true; 
    int count = 0; 
    while (keepGoing) {
        std::getline(std::cin, mystr); 
        std::stringstream sstream(mystr); 
        while (sstream >> x) { 
            std::cout << "added" << x << std::endl; 
            cards.push_back(x); 
        }
        if (std::cin.fail()) {
            keepGoing = false; 
            std::cout <<"fail";
            std::cin.clear(); 
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
            return cards;
        }
        ++count; 
        if (count == 5) return cards; 
    } 
    return cards; 
}

cin controls input from a stream buffer, which put your input characters in a stream buffer, then it was passed to getline . cin控制来自 stream 缓冲区的输入,该缓冲区将您的输入字符放入 stream 缓冲区中,然后将其传递给getline cin ends input when you signaled EOF with Ctrl+D , Ctrl+Z , or Enter .当您使用Ctrl+DCtrl+ZEnter发出EOF信号时, cin结束输入。 See this link detecting end of input with cin .请参阅使用 cin 检测输入结束的此链接。

getline extracts characters from input and appends them to str until it meet one of the end conditions, in your situaton the end condition is the endline character '\n' , because the default delimeter is the endline character. getline从输入中提取字符并将它们附加到 str 直到满足结束条件之一,在您的情况下,结束条件是结束符'\n' ,因为默认分隔符是结束符。 You may define your own delimeter getline(intput, str, $your_delemeter) , and do a little experiment.您可以定义自己的分隔符getline(intput, str, $your_delemeter) ,并做一个小实验。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM