Using scanf to accept user input

前端 未结 5 647
轻奢々
轻奢々 2020-12-06 13:52

gcc 4.4.2

I was reading an article about scanf. I personally have never checked the return code of a scanf.

#include 

int main(void)
         


        
5条回答
  •  感情败类
    2020-12-06 14:30

    scanf() has problems, in that if a user is expected to type an integer, and types a string instead, often the program bombs. This can be overcome by reading all input as a string (use getchar()), and then converting the string to the correct data type.

    /* example one, to read a word at a time */
    #include 
    #include 
    #define MAXBUFFERSIZE   80
    
    void cleartoendofline( void );  /* ANSI function prototype */
    
    void cleartoendofline( void )
    {
        char ch;
        ch = getchar();
        while( ch != '\n' )
            ch = getchar();
    }
    
    main()
    {
        char    ch;                     /* handles user input */
        char    buffer[MAXBUFFERSIZE];  /* sufficient to handle one line */
        int     char_count;             /* number of characters read for this line */
        int     exit_flag = 0;
        int     valid_choice;
    
        while( exit_flag  == 0 ) {
            printf("Enter a line of text (<80 chars)\n");
            ch = getchar();
            char_count = 0;
            while( (ch != '\n')  &&  (char_count < MAXBUFFERSIZE)) {
                buffer[char_count++] = ch;
                ch = getchar();
            }
            buffer[char_count] = 0x00;      /* null terminate buffer */
            printf("\nThe line you entered was:\n");
            printf("%s\n", buffer);
    
            valid_choice = 0;
            while( valid_choice == 0 ) {
                printf("Continue (Y/N)?\n");
                scanf(" %c", &ch );
                ch = toupper( ch );
                if((ch == 'Y') || (ch == 'N') )
                    valid_choice = 1;
                else
                    printf("\007Error: Invalid choice\n");
                cleartoendofline();
            }
            if( ch == 'N' ) exit_flag = 1;
        }
    }
    

提交回复
热议问题