java中像scanf一样多个输入,多个输入由用户动态地在运行时

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.

The test case :

Input

3

1 6 7

2 7 3 4

2 1

Output:

14

16

3

Can we modify scanf() in this way so it can process this dynamic inputs.

I can't take the line as a string input and then split them into numbers.

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);

解决方案

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.

Example: 2 3 4

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

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;

}

Inputs:

3

1 6 7

2 7 3 4

2 1

Output:

14

16

3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值