多个输入由用户动态地在运行时 [英] multiple inputs by user dynamically at runtime
问题描述
如何我们可以采取的整数输入多个数量由用户选择在C运行时。
这里,输入的第一行是的测试用例的数量即可。然后我计算在这种情况下,输入数的总和。
How can we take multiple number of integer inputs by user choice in c in runtime. Here the first line of the input is the number of test cases. Then I am calculating the sum of the input numbers in this case.
测试用例:
输入
3
1 6 7
2 7 3 4
2 1
输出:
14
16
3
我们能修改 scanf()的这种方式,因此它可以处理这个充满活力的投入。
Can we modify scanf() in this way so it can process this dynamic inputs.
我不能走线作为一个字符串输入,然后将它们分割成数。
我们能否利用空间和\\ n双方来决定的数字,因为我们做把字符串作为输入为例: scanf函数(%[^ \\ n],&安培; STR);
Can we use the space and \n both to decide the numbers as we do to take strings as input as an example: scanf("%[^\n]",&str);
推荐答案
答案被BLUEPIXY被他漂亮的code提供。在这里,我们将考虑输入为一对。
The answer was provided by BLUEPIXY by his nice code. Here we will consider inputs as a pair.
要么这将是一个对数和空间的或将是一对数和换行字符的
Either it will be a pair of number and space or it will be a pair of number and newline character.
例如: 2 3 4
因此,在此输入我们采取的对像 - '2
','3
和4 \\ n
。
当我们遇到一个 \\ n
我们停止无限循环。在这里,code云:
So in this input we take as pairs, like - '2', '3
' and '4
\n
'.
When we encounter a \n
we stop the infinite loop. Here the code goes:
#include <stdio.h>
int main(void){
int n;
scanf("%d", &n);
while(n--){
int v, sum = 0;
while(1){
char ch = 0;
scanf("%d%c", &v, &ch);
sum += v;
if(ch == '\n' || ch == 0)
break;
}
printf("%d\n", sum);
}
return 0;
}
输入:
3
1 6 7
2 7 3 4
2 1
输出:
14
16
3
这篇关于多个输入由用户动态地在运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!