Putting numbers separated by a space into an array

前端 未结 3 2005
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 22:43

I want to have a user enter numbers separated by a space and then store each value as an element of an array. Currently I have:

while ((c = getchar()) != \'\         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 23:39

    Small change to your code: only increment i when you read the space:

    while ((c = getchar()) != '\n')
    {
        if (c != ' ')
            arr[i] = arr[i] * 10 + c - '0'; 
        else
            i++;
    }
    

    Of course, it's better to use scanf:

    while (scanf("%d", &a[i++]) == 1);
    

    providing that you have enough space in the array. Also, be careful that the while above ends with ;, everything is done inside the loop condition.

    As a matter of fact, every return value should be checked.

提交回复
热议问题