有两个 cin 的无限循环

Infinite loop with two cin

我有一个函数,我想在其中读取整数,直到我输入一个非整数。我想重复该功能,直到我按下回车键。但是这个角色被传递给了第二个 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;
}