我如何可以在C读取整数输入的一个变化的量? [英] How can I read a varying amount of integer input in C?
问题描述
我会得到三条线的投入。第一行会给我2个整数和第三行会给我1的整数。但第二线可以给我任何数目的整数范围为100 1之间。例如,在输入可能是:
2 1
5 6 1 9 2
10
或可以是:
10 4
5 6
9
可以读取整数输入的第二线成一个整数数组固定数量的整数,但对于不同数量的整数不能这样做。我想,在这种情况下,我应该使用while循环时 scanf()的
找到一个换行符这将打破。我code那怎么办呢?
-
读取行到缓冲区(<一个href=\"http://stackoverflow.com/questions/33568828/how-can-i-read-a-varying-amount-of-integer-input-in-c#comment54915660_33568828\">@John使用使用
与fgets()
或科尔曼)函数getline()
。 -
解析寻找空白可能包含
的'\\ n'
,退出循环,如果发现该字符串。然后调用与strtol()
或的sscanf()
阅读1号。检查是否存在错误太那个函数的返回值。 -
重复上述步骤。
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. But the second line can give me any number of integers ranging between 1 to 100. For example, the input could be:
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. How do I code that?
Read the line into a buffer (@John Coleman) using using
fgets()
orgetline()
.Parse the string looking for whitespace that may contain a
'\n'
, exit loop if found. Then callstrtol()
orsscanf()
to read the 1 number. Check that function's return value for errors too.Repeat above steps.
这篇关于我如何可以在C读取整数输入的一个变化的量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!