A very simple program about "cin", What's the matt

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
User avatar
Yile
New poster
Posts: 17
Joined: Sun Feb 27, 2005 10:36 am
Location: China

A very simple program about "cin", What's the matt

Post by Yile » Tue Jun 07, 2005 4:04 pm

Code: Select all

#include <iostream.h>
void main(){
  int a;
  while(true){
    cin>>a;
    if(cin.fail()){
      cout<<"error"<<endl;
      cin.clear();
    }
    else{
      break;
    }
  }
}
When the input is

Code: Select all

a
Why the output is

Code: Select all

error
error
error
error
error
error
error
error
error
error
error
...
I do use the cin.clear()! But why still the cin doesn't work.
Why?????

User avatar
sahand
New poster
Posts: 19
Joined: Sat Mar 12, 2005 5:56 pm
Location: Halifax, Nova Scotia, Canada
Contact:

Post by sahand » Tue Jun 07, 2005 4:17 pm

Use this:

Code: Select all

#include <iostream.h>
void main(){
  int a;
  while(true){
    cin>>a;
    if(cin.fail()){
      cout<<"error"<<endl;
      cin.clear();
      break;
    }
    else{
      break;
    }
  }
}
cin.clear() does not do what you think it does. read the documentations.

CDiMa
Experienced poster
Posts: 214
Joined: Fri Oct 17, 2003 5:49 pm
Location: Genova

Re: A very simple program about "cin", What's the

Post by CDiMa » Tue Jun 07, 2005 4:20 pm

Yile wrote:I do use the cin.clear()! But why still the cin doesn't work.
Why?????
Clearing cin simply resets the error flag but doesn't remove the offending char from the input stream. You have to cin.ignore(...) to go past it and resume reading...

Ciao!!!

User avatar
Yile
New poster
Posts: 17
Joined: Sun Feb 27, 2005 10:36 am
Location: China

Post by Yile » Wed Jun 08, 2005 1:44 pm

Thank you very much! :)

Post Reply

Return to “C++”