detecting end of input with cin

前端 未结 6 1471
梦毁少年i
梦毁少年i 2020-12-10 06: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



        
相关标签:
6条回答
  • 2020-12-10 06:52

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

    0 讨论(0)
  • 2020-12-10 06:55

    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 */
    }
    
    0 讨论(0)
  • 2020-12-10 06:55

    I usually detect end of cpp stream below:

    while (cin.peek() != EOF) {
      // To do your stuff...
      // NOTE: peek() won't set failbit and badbit when peeking end of stream.
      // So you could use cin.exception() instead of testing manually
      // fail() or bad().
    }
    
    0 讨论(0)
  • 2020-12-10 07:01

    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
    }
    
    
    0 讨论(0)
  • 2020-12-10 07:05

    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>{}};
    
    0 讨论(0)
  • 2020-12-10 07:09

    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
    }
    
    0 讨论(0)
提交回复
热议问题