how to read random number of int in array

后端 未结 4 1406
庸人自扰
庸人自扰 2021-01-28 11:43

i want to read space separated integer into an array and when i press enter it should stop reading at any point of time, how to implement loop for this prog

4条回答
  •  北海茫月
    2021-01-28 12:05

    scanf("%d"... first begins by consuming leading white space. To detect '\n', code should scan leading white-space before calling scanf("%d"....

    To terminate input when a '\n' occurs, first begin looking for it. Suggest using getchar().

    The following code handles OP goals and:
    * Lines beginning with \n
    * Lines with more than N int
    * EOF and non-numeric input

    #include
    #include
    #define N (30)
    
    int main(void) {
      int arr[N];
      int j = 0;
      for (j = 0; j < N; j++) {  // Don't read too many
        int ch;
        while ((ch = getchar()) != '\n' && isspace(ch));
        if (ch == '\n') {
          break;
        }
        // put back ch
        ungetc(ch, stdin);
    
        int cnt = scanf("%d", &arr[j]);
        if (cnt != 1) {
          break;  // Stop if input is EOF or non-numeric
        }
      }
      printf("%d\n", j);
      return 0;
    }
    

提交回复
热议问题