C-如何读取输入 [英] C - How to read inputs

查看:73
本文介绍了C-如何读取输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是家庭作业的一部分,但不是主要部分

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.

以下是输入内容:

3

1 2 9

6

1 1 3 4 4 6

1 1 3 4 4 6

0

因此,基本上,第一个输入是下一个输入的#号的大小。因此,对于3,数组的大小为3,以[1,2,9]为元素,对于6,数组的大小为6,以[1,1,3,4,4,6]为元素

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

当输入为0时,程序终止。

And when the input is 0, the program terminates.

我认为使用while循环并在输入时说[ 0] ='0'并中断,我可以终止程序,但是我不知道如何将其他输入转换为char数组。

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.

您可以看到有空格,所以scanf会将每个整数读入char数组的方式都不同。

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

获得了char的输入后,我相信可以使用atoi来将其恢复为整数...

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;
        }
    }
}

输出对第一个数组,但是之后由于temp [size],它输出一些奇怪的东西。有任何解决这个问题的方法吗?我希望数组的大小成为用户所需大小的大小。 (例如,对于我在上面编写的输入:3和6)

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)

推荐答案

抓取第一个数字应该是微不足道的,然后考虑要读取空格的数字字符串,您可以简单地使用 scanf() 的否定扫描集:

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);

或仅 fgets()

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

然后如您所料,将其放入期间循环等待第一个数字为0。

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

>我相信我可以使用atoi将其恢复为整数

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

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

这篇关于C-如何读取输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆