Which is the best way to get input from user in C?

前端 未结 4 1443
我在风中等你
我在风中等你 2020-11-28 20:59

Many people said that scanf shouldn\'t be used in \"more serious program\", same as with getline.

I started to be lost: if every input fun

4条回答
  •  一生所求
    2020-11-28 21:30

    There are several problems with using scanf:

    • reading text with a plain %s conversion specifier has the same risk as using gets(); if the user types in a string that's longer than what the target buffer is sized to hold, you'll get a buffer overrun;

    • if using %d or %f to read numeric input, certain bad patterns cannot be caught and rejected completely -- if you're reading an integer with %d and the user types "12r4", scanf will convert and assign the 12 while leaving r4 in the input stream to foul up the next read;

    • some conversion specifiers skip leading whitespace, others do not, and failure to take that into account can lead to problems where some input is skipped completely;

    Basically, it takes a lot of extra effort to bulletproof reads using scanf.

    A good alternative is to read all input as text using fgets(), and then tokenize and convert the input using sscanf or combinations of strtok, strtol, strtod, etc.

提交回复
热议问题