我正在编写一个直接从用户输入读取数据的程序,我想知道我如何(没有循环)从标准输入读取所有数据直到 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模板网!
读取输入文件,最快的方法?read input files, fastest way possible?(读取输入文件,最快的方法?)
在 C++ 中读取格式化输入的最简单方法?The easiest way to read formatted input in C++?(在 C++ 中读取格式化输入的最简单方法?)
从 .txt 文件读取到 C++ 中的二维数组Reading from .txt file into two dimensional array in c++(从 .txt 文件读取到 C++ 中的二维数组)
如何在 C++ 中模拟按键按下How to simulate a key press in C++(如何在 C++ 中模拟按键按下)
为什么在 cin.ignore() 之后没有 getline(cin, var) 读取Why doesn#39;t getline(cin, var) after cin.ignore() read the first character of the string?(为什么在 cin.ignore() 之后没有 getline(cin, var) 读取
scanf 格式输入的 cin 类比是什么?What is the cin analougus of scanf formatted input?(scanf 格式输入的 cin 类比是什么?)