how to read random number of int in array

后端 未结 4 1407
庸人自扰
庸人自扰 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 11:50

    Your problem is that scanf will automatically skip over all whitespace (spaces, tabs, newlines) as it looks for the next item. You can make it distinguish between newlines and other whitespace by specifically asking to read in a newline:

    int main() {
        int arr[30]; // results array
        int cnt = 0; // number of results
        while (1) {
            // in the scanf format string below
            // %1[\n] asks for a 1-character string containing a newline
            char tmp[2]; // buffer for the newline
            int res = scanf("%d%1[\n]", &arr[cnt], tmp);
            if (res == 0) {
                // did not even get the integer
                // handle input error here
                break;
            }
            if (res == 1) {
                // got the integer, but no newline
                // go on to read the next integer
                ++cnt;
            }
            if (res == 2) {
                // got both the integer and newline
                // all done, drop out
                ++cnt;
                break;
            }
        }
        printf("got %d integers\n", cnt);
        return 0;
    }
    

    The problem with this approach is that it only recognizes a newline following an integer and will silently skip a line that contains only whitespace (and start reading integers from the next line). If that is not acceptable, then I think the easiest solution is to read the whole line into a buffer and parse the integers from that buffer:

    int main() {
        int arr[30]; // results array
        int cnt = 0; // number of results
        char buf[1000]; // buffer for the whole line
        if (fgets(buf, sizeof(buf), stdin) == NULL) {
            // handle input error here
        } else {
            int pos = 0; // current position in buffer
            // in the scanf format string below
            // %n asks for number of characters used by sscanf
            int num;
            while (sscanf(buf + pos, "%d%n", &arr[cnt], &num) == 1) {
                pos += num; // advance position in buffer
                cnt += 1; // advance position in results
            }
            // check here that all of the buffer has been used
            // that is, that there was nothing else but integers on the line
        }
        printf("got %d integers\n", cnt);
        return 0;
    }
    

    Also note that both of the above solutions will overwrite the results array when there are more than 30 integers on the line. The second solution will also leave some of the input line unread if it is longer than what fits into the buffer. Depending on where your input is coming from, both of these may be problems that need to be fixed before the code is actually used.

    0 讨论(0)
  • 2021-01-28 12:03

    Method 1: Use the return value of scanf() and enter a character once done(Your question doesn't need this as reading till newline will not work but this is one of the ways)

    int d;
    while(scanf("%d",&d) == 1)
    {
       arr[i] = d;
       i++;
    }
    

    Method 2: Use fgets() the read the line and parse the line using strok() and atoi() as shown

    char arr[100];
        fgets(arr,sizeof(arr),stdin);
    
        char *p =strtok(arr, " ");
    
        while(p != NULL)
        {
           int d = atoi(p);
           arr[i++] = d;
           p = strtok(NULL," ");
        }
    
    0 讨论(0)
  • 2021-01-28 12:04

    A good way is to use getchar() and a character to check ENTER in your program by checking ASCII value

    while(1)
        {
            char d;
            d=getchar();
    
              if(d==13 || d==10) break;
                arr[j++]=d-'0';
    
        }
    

    it will terminate as soon as you will press enter. More discussion is already provided on this So post

    0 讨论(0)
  • 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<ctype.h>
    #include<stdio.h>
    #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;
    }
    
    0 讨论(0)
提交回复
热议问题