How to read until EOF from cin in C++(如何从C ++中的cin读取直到EOF)
问题描述
我正在编写一个直接从用户输入读取数据的程序,我想知道我如何(没有循环)从标准输入读取所有数据直到 EOF.我正在考虑使用 cin.get( input, ' ' )
但 ' '
并不是真正的 EOF 字符,它只是读取到 EOF 或 ' '
,以先到者为准.
I am coding a program that reads data directly from user input and was wondering how could I (without loops) read all data until EOF from standard input. I was considering using cin.get( input, ' ' )
but ' '
is not really the EOF character, that just reads until EOF or ' '
, whichever comes first.
还是使用循环是唯一的方法?如果是这样,最好的方法是什么?
Or is using loops the only way to do it? If so, what is the best way?
推荐答案
从 stdin
读取可变数量数据的唯一方法是使用循环.我一直发现 std::getline()
函数效果很好:
The only way you can read a variable amount of data from stdin
is using loops. I've always found that the std::getline()
function works very well:
std::string line;
while (std::getline(std::cin, line))
{
std::cout << line << std::endl;
}
默认 getline()
读取直到换行.您可以指定一个替代终止字符,但 EOF 本身并不是一个字符,因此您不能简单地调用一次 getline()
.
By default getline()
reads until a newline. You can specify an alternative termination character, but EOF is not itself a character so you cannot simply make one call to getline()
.
这篇关于如何从C ++中的cin读取直到EOF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从C ++中的cin读取直到EOF


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01