This question already has answers here:
Infinite loop with cin when typing string while a number is expected
                                
                                    (4个答案)
                                
                        
                                3年前关闭。
            
                    
我有一个函数,要在输入非整数之前要读取整数。我想重复该功能,直到按Enter。但是角色被传递给第二个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;
}

关于c++ - 带有两个cin的无限循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36496378/

10-13 07:50
查看更多