What can I use for input conversion instead of scanf?

前端 未结 8 1063
悲哀的现实
悲哀的现实 2020-11-22 13:27

I have very frequently seen people discouraging others from using scanf and saying that there are better alternatives. However, all I end up seeing is either

8条回答
  •  遇见更好的自我
    2020-11-22 13:45

    What can I use to parse input instead of scanf?

    Instead of scanf(some_format, ...), consider fgets() with sscanf(buffer, some_format_and %n, ...)

    By using " %n", code can simply detect if all the format was successfully scanned and that no extra non-white-space junk was at the end.

    // scanf("%d %f fred", &some_int, &some_float);
    #define EXPECTED_LINE_MAX 100
    char buffer[EXPECTED_LINE_MAX * 2];  // Suggest 2x, no real need to be stingy.
    
    if (fgets(buffer, sizeof buffer, stdin)) {
      int n = 0;
      // add ------------->    " %n" 
      sscanf(buffer, "%d %f fred %n", &some_int, &some_float, &n);
      // Did scan complete, and to the end?
      if (n > 0 && buffer[n] == '\0') {
        // success, use `some_int, some_float`
      } else {
        ; // Report bad input and handle desired.
      }
    

提交回复
热议问题