Finding input end with cin

I want to read a string of integers from a user. I'm not sure how to check if the login has completed. For example, I want to be able to do something like

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

Input Example: 2 1 4 -6

how can i check if there is anything for cin?

+4
source share
3 answers

It is very simple. All you have to do is perform the extraction as a condition:

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

if the extraction fails for some reason (more characters remain, incorrect input, etc.), the cycle will end and the failure will be presented in the input stream.

, C-. std::array<T, N> ( std::vector<T>, ).

, std::vector. , :

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

int temp;

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

,

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

If cinit is still interactive, then there is no concept of “no more input”, because it just waits for the user to provide more input (unless the user has signaled EOFwith Ctrl+ Dor Ctrl+ Z). If you want to process a data string, then get the string from the user (with, say, getline), and then process this input (by extracting from a string stream or similar).

+3
source

Source: https://habr.com/ru/post/1524197/


All Articles