detecting end of input with cin

别等时光非礼了梦想. 提交于 2019-12-29 06:58:13

问题


I want to read a line of integers from the user. I'm not sure how to check to see if the input has ended. For example I want to be able to do something like

int x[MAX_SIZE];
int i = 0;
while(cin.hasNext())
{
  cin >> x[++i];
}

Example input: 2 1 4 -6

how can I check to see if there's any more for cin to take?


回答1:


Yo have to do the following

int temp;

vector<int> v;
while(cin>>temp){
    v.push_back(temp);
}

also you can check for end of input using

if(cin.eof()){
    //end of input reached
}



回答2:


If cin is still interactive, then there's no notion of "no more input" because it will simply wait for the user to provide more input (unless the user has signaled EOF with Ctrl+D or Ctrl+Z as appropriate). If you want to process a line of data, then get a line from the user (with, say, getline) and then deal with that input (by extracting out of a stringstream or similar).




回答3:


It is very straightforward. All you need to do is perform the extraction as the condition:

while (i < MAX_SIZE && std::cin >> x[i++])

if the extraction fails for any reason (no more characters left, invalid input, etc.) the loop will terminate and the failure will be represented in the stream state of the input stream.

Considering best practices, you shouldn't be using static C-arrays. You should be using the compile-time container std::array<T, N> (or std::vector<T> if the former is not supported).

Here is an example using std::vector. It also utilizes iterators which does away with having to explicitly create a copy of the input:

std::vector<int> v{ std::istream_iterator<int>{std::cin},
                    std::istream_iterator<int>{}};


来源:https://stackoverflow.com/questions/21420352/detecting-end-of-input-with-cin

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