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

后端 未结 2 1567
耶瑟儿~
耶瑟儿~ 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: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.
    }
    

提交回复
热议问题