How to read from std::cin until the end of the stream?

大城市里の小女人 提交于 2019-12-29 09:05:54

问题


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.

Edit: Just noticed that std::cin.eof() is always false also in the case of reading form a file.

For a) I could read until \n occures. For b) Edit: 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?

This is what I have for a) ...

char buffer = ' ';
while(std::cin >> std::noskipws >> buffer && buffer != '\n')
{
    // do some stuff with buffer
}

... and b)

char buffer = ' ';
while(std::cin >> std::noskipws >> buffer)
{
    // do some stuff with buffer
}

Also I know there is std::cin.tellg() to get the current position in the stream.

Edit: 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):

  • 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

So how do I do it?


回答1:


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




回答2:


You could use the (old) getline function, which takes a pointer to a char array and can use a delimiter. But you wont be able to ensure that in every case it will read to the eof (as the char buffer might be too small), but using a char-array and not paying attention to the size of it is a very dangerous (and from the point of security catastrophic) thing anyways as it can lead to buffer-overflows which can be easily exploited.

This code should enable you to extract line by line from the input:

char buffer[256];
while(getline(buffer,256,'\n')) { //get a line
   /* do something with the line */
}

This to read a maximum amount of chars:

char buffer[256];
while(getline(buffer,256)) {//get a maximum amount out of the input
   /* do something with the line */
}


来源:https://stackoverflow.com/questions/8234171/how-to-read-from-stdcin-until-the-end-of-the-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!