detecting end of input with cin
Asked Answered
E

7

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?

Excommunicative answered 29/1, 2014 at 1:27 Comment(1)
do not try cin.eof()Cytogenesis
G
10

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
}
Garrison answered 29/1, 2014 at 1:33 Comment(0)
W
6

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).

Words answered 29/1, 2014 at 2:2 Comment(0)
C
4

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>{}};
Cilicia answered 29/1, 2014 at 1:30 Comment(0)
P
3

You might want something like this:

int inp;

while(cin >> inp){  
    ....
    if(cin.peek() == '\n')
        cin.clear(ios::eofbit);
    ....
    }

The while loop runs as long as the I/O is successful. Assuming you want to end input when the line of integers ends, you set the eofbit manually when a \n is encountered. This is checked with the condition if(cin.peek() == '\n'). When the condition is true the while loop terminates. In the example below, I demonstrate how to read a line of integers separated by space into a vector and then print it separated by space

#include<iostream>
#include<vector>
#include<iterator>
#include<algorithm>
using namespace std;

int main(){
    vector<int> coll;
    int inp;

    while(cin >> inp){ 
        if(cin.peek() == '\n')
            cin.clear(ios::eofbit);
        coll.push_back(inp); 
    }

    copy(
        coll.cbegin(),
        coll.cend(),
        ostream_iterator<int>(cout, " ")
    );
    cout << endl;
}

Paperback answered 9/9, 2021 at 3:39 Comment(1)
I was looking exactly for this, thanksAccordance
I
1

using fstream you can do something like this

ifstream ifile("input.txt");
while(!ifile.eof())
{
    /* do something */
}

you can also use this

if(!ifile.is_open())
{
   /* do something */
}
Interdental answered 24/8, 2020 at 11:41 Comment(0)
D
0

The idea is silimar with this code below so you can try :

int tmp;
while(cin >> tmp != NULL){ // C++ or while(scanf("%d", &tmp) != -1) {} for C
     // do something
}

Deepfreeze answered 13/8, 2020 at 9:15 Comment(1)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Disaccharide
N
0

I usually detect end of cpp stream below:

while (cin.peek() != EOF) {
  // To do your stuff...
  // NOTE: peek() will set failbit when peeking end of stream and return EOF(-1).
}
Never answered 9/12, 2020 at 7:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.