使用的getchar()取多个值。多个、getchar

2023-09-11 06:25:47 作者:Avecle soleil丶 手捧阳光

我能以某种方式使用的getchar(),以通过命令行运行,直到我打了'\ N'。 说我想在我的所有输入,如值进行扫描。

Could I somehow use getchar() to run through a command line until I hit a '\n'. Say I want to scan in all the values I enter such as.

21 23 1 78 54'\ N'。我想扫描所有的五个值到一个数组。我无法扫描他们进来是因为每一个值之间的距离呢?或者是有,我们可以用它来做到这一点的函数?

21 23 1 78 54 '\n'. I want to scan all the five values into an array. I am unable to scan them in. Is it because of the spacing between each value? Or is there a function we could use to do it ?

在此先感谢

推荐答案

如果您不使用的getchar()然后我用一个简单的解决方案 scanf函数与%D 转换说明:

If you are not bent on using getchar() then I have a straightforward solution using scanf with the %d conversion specifier:

while (i < ARRAY_SIZE && scanf("%d", &a[i]) == 1)
    i++ ;

%D 转换符告诉 scanf函数来跳过任何前导空格和读取到下一个非数字字符。返回值是成功转换和分配数量。因为我们要读取一个整数值,则返回值应该是1成功。

The %d conversion specifier tells scanf to skip over any leading whitespace and read up to the next non-digit character. The return value is the number of successful conversions and assignments. Since we're reading a single integer value, the return value should be 1 on success.