C - How to read inputs

本秂侑毒 提交于 2019-12-11 11:39:40

问题


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)


回答1:


Grabbing the first number should be trivial, then for the "string of numbers" considering you want to read spaces, you could simply do something like using scanf()'s negated scanset:

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

or just fgets()

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

Then as you guessed put that in a while loop waiting for that first number to be 0.

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

If they're all single digits (as in your example) you can simply subtract the value of '0' from them to get the int value



来源:https://stackoverflow.com/questions/15089140/c-how-to-read-inputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!