以下是一个示例程序,可以从标准输入读取整数,直到文件结束。
#include
int main() {
int num;
while (std::cin >> num) {
std::cout << "读取到整数: " << num << std::endl;
}
return 0;
}
这个程序使用了std::cin
来读取整数。std::cin
返回一个istream
对象,它可以进行输入操作。在while
循环中,我们使用std::cin >> num
来读取一个整数,并将其存储在变量num
中。如果读取成功,则会执行循环体内的代码,打印读取到的整数。如果读取失败(例如遇到文件结束符),则循环终止。
可以通过以下方式来测试程序:
./a.out < input.txt
,其中input.txt
是包含整数的文本文件。当程序读取到文件结束时,循环将终止,程序执行完成。