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


- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- C++ 协变模板 2021-01-01