温馨提示×

C++中怎么正确处理输入流中的EOF

c++
小亿
84
2024-04-18 10:56:05
栏目: 编程语言

在C++中,可以使用while(cin >> input)来处理输入流中的EOF。当输入流中没有更多的数据时,cin >> input会返回false,从而结束循环。

示例代码如下:

#include <iostream>
using namespace std;

int main() {
    int input;
    
    while(cin >> input) {
        // 处理输入数据
        cout << "Input: " << input << endl;
    }
    
    if(cin.eof()) {
        cout << "End of file reached." << endl;
    }
    
    return 0;
}

在上面的代码中,当输入流中没有更多数据时,while(cin >> input)会返回false,循环结束,然后通过cin.eof()来判断是否已经到达文件结尾。

0