Is it possible to use scanf(“%d” &i) and use the first number inputted only, and nothing else?

后端 未结 2 1566
耶瑟儿~
耶瑟儿~ 2021-01-28 23:13

First off, I am not familiar with c at all. It would be great if you treated me like a total beginner, which I am.

So, the problem I have is that I don\'t seem to be ab

相关标签:
2条回答
  • 2021-01-28 23:50

    the program ends because of the character [enter] left in the input buffer.
    You give input value for type then for i and press [enter]. this [enter] is a character left in the input buffer which will be read by next

    scanf("%c",type);
    

    so the loop exits. Therefore use getchar() after

    int ret = scanf("%d", &i);
    

    To clear the input buffer. and the loop will not end unexpectedly.
    Make these changes,

     printf("\t Please input one ASCII code \n"); 
                 int ret = scanf("%d", &i);
                 getchar();          //this will read the [enter] character in input buffer
    /* My aim here is to get the amount of integers the user inputs,*/ 
    /* and use that to categorize, but I think I am failing to do so. */
                 if(ret==1){
    
    0 讨论(0)
  • 2021-01-28 23:56

    In general, I find it better to use fgets() (alternatively, if you are using C99, gets_s() -- although I still prefer fgets() for maximum portability to older compiler environments) for all user-based input, then if necessary use sscanf(), strtol(), and the like to convert the string into other data types, as this will read data by line in a way that is buffer-safe and you won't have to worry about things left in the input buffer. This is especially true for user-based input which is never well-formed (due to typos, etc). scanf() really only works well when reading from well-formed input files.

    See the comp.lang.c FAQ which describes some of the problems that often occur when using scanf() in detail, including the problem you are seeing above, where inputs seem to be getting skipped:

    • http://c-faq.com/stdio/scanfprobs.html
    • http://c-faq.com/stdio/scanfhang.html
    • http://c-faq.com/stdio/scanfinterlace.html
    • http://c-faq.com/stdio/scanfjam.html

    To find out more about any C standard library function, at a linux command prompt (or Google) type: man 3 fgets and so on.

    • fgets: http://linux.die.net/man/3/fgets
    • sscanf: http://linux.die.net/man/3/sscanf
    • strtol: http://linux.die.net/man/3/strtol

    Example:

    char buffer[256], type;
    fgets( buffer, sizeof(buffer), stdin );
    if( sscanf( buffer, "%c", &type ) == 1 ) {
        // Was able to read a char from the buffer, now you can use it.
    }
    else {
        // Wasn't able to read a char from the buffer.  handle it if required.
    }
    
    0 讨论(0)
提交回复
热议问题