CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2010
    Posts
    32

    Unhappy cin.clear() question: Not able to clear the status of cin stream

    Hi all,
    I have a small piece of code that I want to do a series of function of while(cin>>temp) kind of operation.
    But if i input 8 and 9 then enter an non-integer number, the program run past the next function of while(cin>>temp).

    In the console it's something like this:
    For the 0th element:
    8
    9
    g
    For the 1th element:
    For the 2th element:
    For the 3th element:
    For the 4th element:
    17 0 0 0 0

    I used cin.clear() but it still doesn't work. Could someone help me on that? Thanks a lot.

    Code:
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    void c_plus_plus(vector<int> &ivec, int n){
      int temp;
      cout<<"For the "<<n<<"th element:"<<endl;
      while(cin>>temp)
        ivec[n]=ivec[n]+temp;
    }
    
    int main(){
      
      vector<int> ivec(5);
    
      for(int i=0;i<5;i++){
        c_plus_plus(ivec, i);
        cin.clear(iostream::failbit);
      }
    
      for(int i=0;i<5;i++)
        cout<<ivec[i]<<" ";
    
    
      return 0;
    }

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725

    Re: cin.clear() question: Not able to clear the status of cin stream

    It is not enough to clear the streams internal flags, you need to remove
    the offending characters from the stream's buffer. This is usually done
    using the ignore() member function:

    Code:
      for(int i=0;i<5;i++)
      {
        c_plus_plus(ivec, i);
        cin.clear();
        cin.ignore(1000,'\n');
      }

  3. #3
    Join Date
    Dec 2010
    Posts
    32

    Re: cin.clear() question: Not able to clear the status of cin stream

    Thanks a lot Philip!
    u r the best.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured