如何从std :: cin读取直到流结束? [英] How to read from std::cin until the end of the stream?
问题描述
我的问题是,我想从 std :: cin
中读取输入,但是不知道输入多长时间。另外我还必须
我有两种处理方法:
a)用户输入文本,当他按下[ENTER]时,程序停止读取。
b)用户将 std :: cin
重定向到文件(例如 .\a.oput<文件
)可以容纳多行。
My problem is, that I want to read the input from std::cin
but don't know how long the input is. Also I have to char
and can't use std::string
.
There are two ways I have to handle:
a) The user inputs text and when he hits [ENTER] the program stops reading.
b) The user redirects std::cin
to a file (like .\a.oput < file
) which can hold multiple lines.
编辑:刚刚注意到,std :: cin.eof()始终为false
Just noticed that std::cin.eof() is always false also in the case of reading form a file.
对于a)我可以读取直到\n出现。对于b)编辑:否(我可以读到std :: cin.eof()出现。)
但是当我不知道我要的是a)还是ab )问题,我该如何中断阅读过程?
For a) I could read until \n occures. For b) No (I could read until std::cin.eof() occures.) But when I don't know whether I'm getting an a) or a b) problem, how can I break the reading process?
这就是我的a)...
This is what I have for a) ...
char buffer = ' ';
while(std::cin >> std::noskipws >> buffer && buffer != '\n')
{
// do some stuff with buffer
}
...和b)
char buffer = ' ';
while(std::cin >> std::noskipws >> buffer)
{
// do some stuff with buffer
}
我也知道有 std :: cin.tellg()
编辑:因此,似乎在文件输入流终止的情况下, std :: cin>>的方式std :: noskipws>>缓冲区
获取 false
。
上面的代码对a)的作用:
So it seems like in case of the file the input streams gets terminated, in the way that std::cin >> std::noskipws >> buffer
gets false
.
What the code above does for a):
- 它等待用户输入并按[ENTER]
- 然后循环遍历用户在最后一行输入的每个字符。
- 然后再次等待用户进行输入,然后按[ ENTER]
- 无限等待处理循环
- It waits for the user to make an input and press [ENTER]
- Then it loops through every char entered by the user on the last line.
- Then it waits again for the user to make an input and press [ENTER]
- Infinite-waiting-processing-loop
那我该怎么办?
推荐答案
您可以要求输入始终以EOF结尾(意思是要求 ^ D的命令行
被按下),然后照常使用b的过程。然后,这也会启用来自cmdline的多行输入
You could require the input to always end EOF (meaning from commmand line requiring ^D
to be pressed) and then use the process for b as always. This would then enable multiline input from cmdline as well
这篇关于如何从std :: cin读取直到流结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!