具有两个cin的无限循环

Infinite loop with two cin

本文关键字:两个 cin 无限循环      更新时间:2023-10-16

我有一个函数,我想在其中读取整数,直到输入非整数。我想重复这个功能,直到我按下回车键。但角色被传递到第二个cin,它变成了一个无限循环。

void  read () {
    int  x;
    while ( cin >> x );
}
int main () {
    char  a;
    do {
        read ();
        cin.ignore (256, 'n')
        cin >> a;
    } while ( a != 'n' )
}

1)您忘记删除std::cin中的失败位;使用clear()

2) 为了检测空输入,我建议使用std::stringstd::getline()

我建议像

#include <iostream>
#include <string>
void  read () {
    int  x;
    while ( std::cin >> x ) ;
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<int>::max(), 'n');
}
int main () {
    std::string  b;
    do {
        read();
        std::getline(std::cin, b);
    } while ( false == b.empty() );
    return 0;
}