简体   繁体   English

如何在C中读取变化量的整数输入?

[英]How can I read a varying amount of integer input in C?

I will be getting three lines of input. 我将获得三行输入。 The first line will give me 2 integers and the third line will give me 1 integer. 第一行将给我2个整数,第三行将给我1个整数。 But the second line can give me any number of integers ranging between 1 to 100. For example, the input could be: 但是第二行可以给我整数,范围是1到100。例如,输入可以是:

2 1
5 6 1 9 2
10

or could be: 或可能是:

10 4
5 6
9

I can read the second line of integer input into an integer array for a fixed number of integers, but cannot do so for a varying number of integers. 我可以将整数输入的第二行读取到整数数组中,以获取固定数量的整数,但不能读取不同数量的整数。 I suppose, in this case, I should use a while loop which will break when scanf() finds a newline. 我想在这种情况下,我应该使用while循环,当scanf()找到换行符时,它将中断。 How do I code that? 我该如何编码?

  1. Read the line into a buffer ( @John Coleman ) using using fgets() or getline() . 使用fgets()getline()将行读入缓冲区( @John Coleman getline()

  2. Parse the string looking for whitespace that may contain a '\\n' , exit loop if found. 解析字符串以查找可能包含'\\n'空格,如果找到则退出循环。 Then call strtol() or sscanf() to read the 1 number. 然后调用strtol()sscanf()读取1号。 Check that function's return value for errors too. 还要检查该函数的返回值是否有错误。

  3. Repeat above steps. 重复上述步骤。

I am actually a newbie in programming and am unaware of most of the functions. 我实际上是编程的新手,并且不了解大多数功能。 The only string functions I know of are strlen() and strcmp() . 我知道的唯一字符串函数是strlen()strcmp() And my i\\o function knowledge is limited to printf() and scanf() . 我的I \\ o函数知识仅限于printf()scanf()

Anyhow, I solved my problem in this way: 无论如何,我以这种方式解决了我的问题:

int a[101];
int i, num;
char ch;

for (i = 0; i < 101; i++)
    a[i] = 0;

while (1)
{
    scanf("%d%c", &num, &ch);
    i = num;
    a[i] = num;
    if (ch == '\n')
        break;
}

This works! 这可行! The value of num had to be equal to the value i because my program needed it. num的值必须等于i因为我的程序需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM