开发者

Simply C loop is driving me nuts

So I have only ever programmed in c++, but I have to do a small homework that requires the use of c. The proble开发者_如何转开发m I encountered is where I need a loop to read in numbers separated by spaces from the user (like: 1 5 6 7 3 42 5) and then take those numbers and fill an array.

the code I wrote is this:

int i, input, array[10];

for(i = 0; i < 10; i++){
scanf("%d", &input);
array[i] = input;
}

EDIT: added array definition. any suggestions or hints would be very highly appreciated.


Irrespective of whatever is wrong here, you should quickly learn to NEVER write code that does not check the return value from any API call that you make. scanf returns a value, and you have to be interested in what it says. If the call fails, your logic is different, yes?

Perhaps in this case it would tell you what's going wrong. The docs are here.

Returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned.


This code working good.

If your numbers is less than 10, then you must know how many numbers is before you start reading this numbers, or last number must be something like 0 to terminate output then you can do while(true) loop, but for dynamically solution you must read all line into string and then using sscanf to reading numbers from this string.


You need the right #include and a proper main. The following works for me

#include <stdio.h>
int main(void) {

    /* YOUR CODE begin */
    int i, input, array[10];
    for (i = 0; i < 10; i++) {
        scanf("%d", &input);
        array[i] = input;
    }
    /* end of YOUR CODE */

    return 0;
}


i'm not a c programmer but i can suggest an algorithm which is to use scanf("%s",&str) to read all the input into a char[] array then loop over it and test using an if statment if the current char is a space, if it is then add the preceeding number to the array

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜