Thread: infinite loop?

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    8

    infinite loop?

    i have a problem:
    Code:
    int x=0;
      while(x!=6)
      {
       cout<<"in the loop"<<endl;
       cin>>x;
       
      }
    when entering a char instead of an int as an input, the loop won't stop running.
    How do I fix it? I want it to enter the loop normally, and ask me for a new input(like it does with any integer other than 6..).
    Thanks!

  2. #2
    Registered User
    Join Date
    Mar 2010
    Posts
    583
    You could just use a char instead.

    Code:
      char x;
      while (x != '6')
      ....
    When x is an int, cin>>x will only read an int from the input. If there is a char there, it'll do nothing (leaving the char there) and next time through the loop, the same char will still be there.... infinite loop.

    I'd just use a char, and convert it back to an integer at a later point if I need to.

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    8
    thanks good idea, i'll do it with a string though, cause inside the loop i have options and when getting an input of a char, 12 (for example) is just like 1.

  4. #4
    The larch
    Join Date
    May 2006
    Posts
    3,573
    If cin expects a number but is given something else, it switches into an error state. Any following input statements will fail without managing to consume any of the input, unless you correct the situation.

    So in the general case
    Code:
    int x=0;
      while(x!=6)
      {
       cout<<"in the loop"<<endl;
       if (!(cin>>x)) {
          cin.clear(); //reset the error state
          cin.ignore(1000, '\n'); //discard unsuitable input (just assuming they didn't type more than 1000 characters, consult FAQs for more correct ways)
       }
        
      }
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  5. #5
    Registered User
    Join Date
    Nov 2011
    Posts
    8
    thx a lot it's what i was looking for.
    Last edited by ooopa; 11-19-2011 at 09:52 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 10-14-2011, 11:33 PM
  2. infinite loop
    By leahknowles in forum C Programming
    Replies: 2
    Last Post: 03-31-2011, 03:40 PM
  3. infinite loop
    By ssjnamek in forum C++ Programming
    Replies: 11
    Last Post: 09-25-2005, 05:08 PM
  4. stays in loop, but it's not an infinite loop (C++)
    By Berticus in forum C++ Programming
    Replies: 8
    Last Post: 07-19-2005, 11:17 AM
  5. Why does cin>> go into an infinite loop
    By Panopticon in forum C++ Programming
    Replies: 2
    Last Post: 02-03-2003, 12:48 AM