|
-
April 7th, 2011, 10:30 PM
#1
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;
}
-
April 8th, 2011, 06:08 AM
#2
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');
}
-
April 8th, 2011, 07:37 AM
#3
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|