how to read random number of int in array

后端 未结 4 1447
庸人自扰
庸人自扰 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: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," ");
        }
    

提交回复
热议问题