scanf unknown number of integers, how to end loop?

后端 未结 1 906
北荒
北荒 2020-12-07 05:38

In class I need to use scanf to get integers to work with. Problem is I do not know to end the while loop. I wait for \'\\n\' in the c

相关标签:
1条回答
  • 2020-12-07 06:08

    while(scanf("%d%c", &numbers, &ch)) { if((ch == '\n') .... has a couple of problems.

    1. If the line of input has only white-space like "\n" or " \n", scanf() does not return until non-white-space is entered as all leading white-spaces are consumed by "%d".

    2. If space occurs after the int, the "\n" is not detected as in "123 \n".

    3. Non-white-space after the int is discarded as in "123-456\n" or "123x456\n".


    how to end loop?

    Look for the '\n'. Do not let "%d" quietly consume it.

    Usually using fgets() to read a line affords the more robust code, yet sticking with scanf() the goal is to examine leading white-space for the '\n'

    #include <ctype.h>
    #include <stdio.h>
    
    // Get one `int`, as able from a partial line.
    // Return status:
    //   1: Success.
    //   0: Unexpected non-numeric character encountered. It remains unread.
    //   EOF: end of file or input error occurred.
    //   '\n': End of line.
    // Note: no guards against overflow.
    int get_int(int *dest) {
      int ch;
      while (isspace((ch = fgetc(stdin)))) {
        if (ch == '\n') return '\n';
      }
      if (ch == EOF) return EOF;
      ungetc(ch, stdin);
      int scan_count = scanf("%d", dest);
      return scan_count;
    }
    

    Test code

    int main(void) {
      unsigned int_count = 0;
      int scan_count;
      int value;
      while ((scan_count = get_int(&value)) == 1) {
        printf("%u: %d\n", ++int_count, value);
      }
      switch (scan_count) {
        case '\n': printf("Normal end of line.\n"); break;
        case EOF: printf("Normal EOF.\n"); break;
        case 0: printf("Offending character code %d encountered.\n", fgetc(stdin)); break;
      }
    }
    
    0 讨论(0)
提交回复
热议问题