problem with cin

int main()
{
again: // a label
int i;
cout<<"enter i "<<endl;
cin>>i ;

if ( cin.fail())
{
cin.ignore(256);
goto again; // if fail then goto again
}
else
{
cout<<"i is : "<<i<<endl;
}
return 0;
}


when suppose i enter a into i which does the stream bad
and when exucation goes to again ... then the programm sort of goes in an infinite loop ,,, meaning it dsnt take cin from the console agan :(
can sm bdy plz help
use try and catch bro!!!
You should not be using goto and labels! C++ has it's own control structures to do tasks like these: http://www.cplusplus.com/doc/tutorial/control/

I'm not sure what the point was in this program but try running this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main() 
{
      int i = 0;

      cout << "Enter i: ";
      cin >> i;
      cin.ignore(); // ignore the newline character left in the stream from cin

      if(cin.fail())
            cout << "\nThe failbit flag has been set\n";
      else
            cout <<  "The stream is good to use\n";

      cin.get();
      return 0;
}
Hi,

The above program is right. But there is no issue if you use GOTO statement in C++. You can use GOTO unconditional jump statement in C++ too.


Syntax of GOTO Statement is :


1
2
3
4
5
6
7
8
9
...................
                                  if (condition)
                                 goto label;
                                  ...............
                                  .................
                                 .................
                                 label: 
                                 .................
                                 .................  


A goto statement can transfer the control to any place in the proram.


improve your basic knowledege in C and C++ by going through some tutorials.

http://www.wiziq.com/tutorial/762-C-Basic-Introduction

Thanks
Kolla Sanjeeva Rao










You're right it can. By would you when you have other more contollable means of performing the same task. The goto statement makes it hard for you to follow your program whilst using the control structures implemented in the C++ language makes it much easier. So yes, there is an issue.
Topic archived. No new replies allowed.