温馨提示×

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

c++
小亿
136
2024-04-18 10:56:05
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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()来判断是否已经到达文件结尾。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:C语言读取中EOF的正确处理方式

0