declared int but entered a char

This is a discussion on declared int but entered a char within the C Programming forums, part of the General Programming Boards category; #include <stdio.h> int main() { int n; printf("Please enter one integer: "); scanf("%d", &n); printf("Entered integer = \n"); return 0; ...

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    22

    Question declared int but entered a char

    #include <stdio.h>

    int main()
    {
    int n;
    printf("Please enter one integer: ");
    scanf("%d", &n);

    printf("Entered integer = \n");

    return 0;
    }

    In this program I prompted the user to enter their desire integer value but when the user accidentally or purposely enter an alphabet, the program generated an error. How do I prevent this kind of problem. Is it we have to declare a buffer first, then copy what ever inside the buffer which is a valid integer into 'int n'? If yes, how? If no, any other way?

  2. #2
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    You can check the return value of the scanf function

    Code:
    #include <stdio.h> 
    
    int main() 
    { 
        int n; 
        printf("Please enter one integer: "); 
        if(scanf("%d", &n))
            printf("Entered integer = %d\n", n); 
        else
            printf("This is not a number\n");
    
        return 0; 
    }

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    scanf will try to read the data type you tell it to, if those data types do not match scanf will choke on it and cause an error. A way around this is to avoid scanf (it's lame anyway, so nothing lost) and read everything as a string, then convert it accordingly:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main ( void )
    {
      char buffer[BUFSIZ];
      printf ( "Enter a number: " );
      if ( fgets ( buffer, sizeof buffer, stdin ) != NULL )
        printf ( "%d\n", atoi ( buffer ) );
      else
        printf ( "Error: Input validation\n" );
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

  4. #4
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    You can use the fgets function but you need to check if the string begins with an integer (atoi returns a zero on error).
    Code:
    #include <ctype.h>
    
    if(isdigit(buffer[0]))
    {
        /* It's (begins with) an integer */
    }

  5. #5
    Registered User
    Join Date
    Mar 2002
    Posts
    22

    Talking Ahem! another problem

    First of all, thank you for replying but there is a problem in this source code (posted by 'Prelude'). When I accidentally or purposely entered a float number something like this 1.23, it doesn't print the expected answer or the 'else' statement. When I entered an alphabet, it printed zero (the else statement did not execute) but when I entered key something like ctrl 'z', 'x' and etc the else statement was executed.



    Problem in the source code posted by 'Monster'.
    When I accidentally or purposely entered a float number like 1.33, it printed the integer number only (this is true because I declared an 'int n'). How do I actually warn the user that he or she has entered an invalid integer.


    Sorry for being so fussy.


  6. #6
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680

    Re: Ahem! another problem

    Originally posted by lockpatrick
    Sorry for being so fussy.
    No problemo, if we stop answering your questions you know it's too fussy. Here's something you can try. Check all characters in your buffer with the isdigit function (but not the last character because this is the newline character).
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main ( void )
    {
        unsigned int i;
        char buffer[BUFSIZ];
        printf ( "Enter a number: " );
        if ( fgets ( buffer, sizeof buffer, stdin ) != NULL )
        {
            /* watch out for the ';' at the end of the next line (for) */
            for(i = 0; (i < strlen(buffer)-1) && isdigit(buffer[i]); i++) ;
    
            if(i == strlen(buffer)-1)
                printf ( "%d\n", atoi ( buffer ) );
            else
                printf("Invalid number\n");
        }
        else
            printf ( "Error: Input validation\n" );
    
      return 0;
    }

  7. #7
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Perhaps you should have mentioned the possibility of floating point values being entered, if I may quote you:
    In this program I prompted the user to enter their desire integer value but when the user accidentally or purposely enter an alphabet, the program generated an error.
    Nowhere do I see the mention of float, you specifically said integer. If you want full validation checking, then let us know so that we can answer your question effectively.
    Code:
    #include <stdio.h>
    #include <ctype.h>
    #include <stdlib.h>
    #include <string.h>
    
    int validate ( char *a )
    {
      unsigned x;
      for ( x = 0; x < strlen ( a ); x++ )
        if ( !isdigit ( a[x] ) ) return 1;
      return 0;
    }
    
    int main ( void )
    {
      int i;
      char buffer[BUFSIZ];
      printf ( "Enter a number: " );
      if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
        buffer[strlen ( buffer ) - 1] = '\0';
        if ( validate ( buffer ) == 0 ) {
          i = atoi ( buffer );
          printf ( "%d\n", i );
        }
        else
          printf ( "Error: Input validation\n" );
      }
      else
        printf ( "Error reading input\n" );
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. Replies: 26
    Last Post: 11-30-2007, 02:51 AM
  3. Game Won't Compile
    By jothesmo in forum C++ Programming
    Replies: 2
    Last Post: 04-01-2006, 03:24 PM
  4. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 04:26 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21