我正在编写一个直接从用户输入读取数据的程序,我想知道我如何(没有循环)从标准输入读取所有数据直到 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!