Thread: infinite while loop

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    58
    Let say if I put it this way, when I try to submit a char, it would have return me an error message. But I still couldn't stop the loop from looping. Do I need to flush or anything ? So that the function can stop at the scanf everytime I enter a char ?

    Code:
    while(sel_case != 0)
    {
       if ( scanf( "%d", &sel_case ) == 1 )
      {
    
        switch(sel_case)
        {
              case 1:  
                            test1();
              break;
             
             ~ case 10
        }
       else
       {
           printf("Wrong input!!");
       }
    
    }

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Your loop won't stop because once the stream ( stdin in your case ) has an error it won't let you input anything in the next pass. One way would be to call
    clearerr(stdin); if the input has failed.
    But better still would be to use fgets() to read a line of input into a char buffer and use sscanf() to extract the data you want.
    Kurt

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 06-14-2009, 11:24 PM
  2. Cosine fucntion and infinite loop.
    By youareafever in forum C Programming
    Replies: 2
    Last Post: 11-07-2008, 04:45 AM
  3. Infinite Loop with GetAsyncKeyState
    By guitarist809 in forum Windows Programming
    Replies: 1
    Last Post: 04-18-2008, 12:09 PM
  4. Switch statement = infinite loop
    By Lucid003 in forum C++ Programming
    Replies: 10
    Last Post: 10-10-2005, 12:46 AM
  5. 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