1

it's part of the homework, but it's not the main part

I already made the main function by manually changing the data by myself, but I really don't get how to read the user inputs correctly.

Here are what the inputs look like:

3

1 2 9

6

1 1 3 4 4 6

0

So basically the first input is the size of the # of the next inputs. So for 3, the array is size 3 with [1,2,9] being the elements, and for 6, the array size is 6 with [1,1,3,4,4,6] being the elements

And when the input is 0, the program terminates.

I think by using a while loop and saying when input[0] = '0' and break, I can terminate the program, but I don't know how to get the other inputs into a char array.

As you can see, there are spaces, so the scanf will read every integers differently into the char array.

After I get the inputs that are char, I believe I can use atoi to make it back to integers...

So, help me how I should code in order to get the user inputs correctly...

Maybe this was too vague: here is the version I kinda want:

while(1)
{
    scanf("%d", &ui);

    if(ui == 0)
    {
        break;
    }
    else
    {   
        size = ui;
        int temp[size];

        for(c = 0; c < size; c++)
        {
            scanf("%d", &input);
            temp[c] = input;
        }
    }
}

The output is good for the first array, but after that because of the temp[size], it outputs something weird. Any way to fix this? I want the size of the array to be the size of the user's wanted size. (e.g. for the input i've written above: 3 and 6)

4

1 回答 1

2

抓取第一个数字应该是微不足道的,然后对于“数字字符串”考虑到您想要读取空格,您可以简单地执行类似使用scanf()的否定扫描集的操作:

char input[100];
scanf("%99[^\n]", input);

要不就fgets()

char input[100];
fgets(input, sizeof input, stdin);

然后就像你猜的那样,把它放在一个while循环中,等待第一个数字为 0。

> I believe I can use atoi to make it back to integers

如果它们都是个位数(如您的示例中),您可以简单地'0'从它们中减去的值来获得int

于 2013-02-26T12:32:33.147 回答