C++ 读到C+中的新行+;以无限循环进行

C++ 读到C+中的新行+;以无限循环进行,c++,c++11,cin,C++,C++11,Cin,给定以下程序 #include <iostream> #include <string> using namespace std; int main() { int integer; cin >> integer; if (!cin) { string str; char ch; while ((ch = cin.get()) != '\n') { cout &l

给定以下程序

#include <iostream>
#include <string>
using namespace std;

int main() {
    int integer;
    cin >> integer;
    if (!cin) {
        string str;
        char ch;
        while ((ch = cin.get()) != '\n') {
            cout << "scanning" << endl;
            cout << "got " << static_cast<int>(ch) << endl;
        }
    }
    return 0;
}
末尾有一个换行符,为什么程序会进入无限循环?在文件末尾遇到换行符后,它不应该停止吗?我不断获取
ch
的值,作为
-1
获取

谢谢


注意
cin.ignore()

int integer;
cin >> integer;
if (!cin) {
    cin.clear(); // If an error occurred, we need to clear it!
    ...

然后,如果在
std::cin
(类型)上出现错误,则需要清除它:

int integer;
cin >> integer;
if (!cin) {
    cin.clear(); // If an error occurred, we need to clear it!
    ...

然后,解决方案是使用
cin.clear()
从失败状态恢复,然后重试扫描直到换行。

解决方案是使用
cin.clear()
从失败状态恢复,然后重试扫描直到换行。

这样做,然后当我扫描到最后尝试查找换行时,我手动在换行符中添加了一个无限循环。就是这样,我必须
cin.ignore()
?没有,没有代码来清除错误,所以cin总是出错。显然,我的大脑今天不能正常工作。很抱歉,是这样的,当我扫描到最后试图找到一个换行符时,我得到一个我手动添加到一个换行符中的无限循环。就是这样,我必须
cin.ignore()
?没有,没有代码来清除错误,所以cin总是出错。显然,我的大脑今天不能正常工作。对不起,不!它只会停止无限循环,但没有正确的结果!尝试{cin>>整数;if(cin.fail())throw;}catch(…){cout no!它只停止无限循环,但没有任何正确的结果!尝试{cin>>整数;if(cin.fail())throw;}catch(…){cout