如何阅读,直到EOF从cin C ++ [英] How to read until EOF from cin in C++
问题描述
我编写一个程序,直接从用户输入读取数据,并想知道如何(无循环)从标准输入读取所有数据,直到EOF。我正在考虑使用 cin.get(input,'\0')
,但'\0'
真的是EOF字符,只读到EOF或'\0'
(以先到为准)。
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, '\0' )
but '\0'
is not really the EOF character, that just reads until EOF or '\0'
, 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().
这篇关于如何阅读,直到EOF从cin C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!