Thread: scanf and integer problems

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    11

    scanf and integer problems

    Hello.
    I am currently having problems scanning in an integer to be used for a menu selection.
    All goes well with the program until you enter in a non integer value; the program will go into an infinite loop and eventually crash.

    I am using scanf to take input from an int

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You probably should read this:

    STDIN pitfalls

    also, you post the code you are using
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    11
    I don't know which technique you are using for menu selection. I will give you the two way to select the menu.In these ways there is no problem as you mentioned.

    Try this,
    Code:
    main ( int argc, char *argv[] )
    {
            int i;
            while(1)
    {
            printf ( "Enter the value:"  );
            scanf("%d",&i);
            switch(i)
            {
                    case 0:
                            printf( "Valid\n");
                            break;
                    default:
                            printf("Default\n");
                            break;
            }
    }
    }
    
    Another way:
    
    while(1)
            {
            printf ( "Enter the value:"  );
            scanf("%d",&i);
                    if(i==1) {
                            printf ( "Value is 1\n"  );
                    }
                    else if(i==2) {
                            printf ( "Value is 2\n"  );
                    }
                    else
                            break;
            }
    If my understanding is wrong , revert me back.

  4. #4
    Registered User UltraKing227's Avatar
    Join Date
    Jan 2010
    Location
    USA, New york
    Posts
    123
    Try This:

    Code:
    #include <ctype.h>
    #include <stdio.h>
    #include <conio.h>
    
    int choice = 0;
    
    int GetInt();
    
    int main()
    {
     while(1 == 1)
     {
      printf("1) Start Program\n");
      printf("2) End Program\n");
      choice = GetInt();
      if (choice == 1)
       printf("Starting a new program...\n");
      if (choice == 2)
       exit(1);
     }
    }
    
    int GetInt()
    {
     /* Init a Char variable with value -1 to 
        not jump out of the loop.*/
     char c = -1;
     /* Loop until the Condition is invalid. */
     while (c > 9 || c < 0)
     {
     c = getch(); /* Get Input*/
     c -= 48; /* Subtract C by 48. E.G '0' = 48 so 
                 Subtracting C by 48 gets us an 
                 Integer Zero */
     }
     return c; /* Return Whatever is in C */ 
    }

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by UltraKing227
    Try This:
    Before you do so, be warned that <conio.h> and getch() and non-standard.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Jul 2009
    Location
    Croatia
    Posts
    272
    You should check how scanf actually works.

    This is the problem when students are given functions which they dont know how they ACTUALLY work.

    SCANF function will read the input depending on its argument.

    If its %d, it will read an integral number - if the character readed from the file (in this case stdin) isnt a number, it will push the character back on the input.

    So the next call to the same scanf will do the same; do nothing - just push the readed char back to input.
    All goes well with the program until you enter in a non integer value; the program will go into an infinite loop and eventually crash.
    I hope its clear to you WHY the program crashes now.

    You could fix this problem by checking if scanf returned 1 (number of args successfully read).

    If its 1, proceed. If 0, fprintf(stderr "errormsg"); and exit or do whatever you want.

    Imo in error case you could write a function skipline(void) which getchars() the rest of the line.


    Also have in mind you need to check EOF when using scanf, as scanf returns specifically EOF when it occurs. Not 0 or 1.


    I'd most likely do it with fgets() and atoi. Check out those functions. Or you could write your own getint() which would be even better as fgets has some limitations.
    Last edited by Tool; 02-27-2010 at 07:16 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Integer partitioning
    By muhFah in forum C Programming
    Replies: 1
    Last Post: 09-18-2009, 10:37 AM
  2. Replies: 2
    Last Post: 02-20-2005, 01:48 PM
  3. Scanf and integer...
    By penny in forum C Programming
    Replies: 3
    Last Post: 04-24-2003, 06:36 AM
  4. Please help debug
    By Wexy in forum C Programming
    Replies: 2
    Last Post: 11-11-2002, 12:40 AM
  5. help with switch statements
    By Wexy in forum C Programming
    Replies: 3
    Last Post: 11-06-2002, 05:44 PM