我如何可以在C读取整数输入的一个变化的量? [英] How can I read a varying amount of integer input in C?

查看:157
本文介绍了我如何可以在C读取整数输入的一个变化的量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会得到三条线的投入。第一行会给我2个整数和第三行会给我1的整数。但第二线可以给我任何数目的整数范围为100 1之间。例如,在输入可能是:

  2 1
5 6 1 9 2
10

或可以是:

  10 4
5 6
9

可以读取整数输入的第二线成一个整数数组固定数量的整数,但对于不同数量的整数不能这样做。我想,在这种情况下,我应该使用whil​​e循环时 scanf()的找到一个换行符这将打破。我code那怎么办呢?


解决方案

  1. 读取行到缓冲区(<一个href=\"http://stackoverflow.com/questions/33568828/how-can-i-read-a-varying-amount-of-integer-input-in-c#comment54915660_33568828\">@John使用使用与fgets()或科尔曼)函数getline()


  2. 解析寻找空白可能包含的'\\ n',退出循环,如果发现该字符串。然后调用与strtol()的sscanf()阅读1号。检查是否存在错误太那个函数的返回值。


  3. 重复上述步骤。


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?

解决方案

  1. Read the line into a buffer (@John Coleman) using using fgets() or getline().

  2. Parse the string looking for whitespace that may contain a '\n', exit loop if found. Then call strtol() or sscanf() to read the 1 number. Check that function's return value for errors too.

  3. Repeat above steps.

这篇关于我如何可以在C读取整数输入的一个变化的量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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