简体   繁体   English

使用scanf()读取c中未知数量的整数

[英]Use scanf() to read an unknown number of integers in c

I need to read an unknown number of rows, each containing an unknown number of integers, this number varying from row to row.我需要读取未知数量的行,每行包含未知数量的整数,这个数字因行而异。

The integers are separated from each other by a single space and there is no space at the end of the line.整数之间用一个空格隔开,行尾没有空格。

The output being the sum of all integers. output 是所有整数的总和。

exemple input:示例输入:

5
2 2
4 4 4
6 6
3 3

output: 39 output: 39

The fact that the numbers are entered over several lines is actually irrelevant.分几行输入数字这一事实实际上是无关紧要的。 Basically you just want to sum up numbers entered by the user until the input stream ends.基本上,您只想对用户输入的数字求和,直到输入 stream 结束。

You probably want something like this:你可能想要这样的东西:

#include <stdio.h>

int main() {    
  int sum = 0;
  int number;

  while (scanf("%d", &number) == 1)
  {
    sum += number;
  }

  printf("Sum of all numbers is %d\n", sum);
}

End the input with Ctrl + D .使用Ctrl + D结束输入。

Example of execution:执行示例:

1 2 3
4 5
6 7
8
Sum of all numbers is 36

Press Ctrl + D after entering 8 .输入8后按Ctrl + D。

Explanation of while (scanf("%d", &number) == 1) while (scanf("%d", &number) == 1)的解释

scanf returns the number of items successfully scanned or EOF when the input stream ends.当输入 stream 结束时, scanf返回扫描成功的项目数或EOF So here we decide to stop the loop if scanf returns anything else than 1 (meaning that the user has either pressed Ctrl + D triggering an EOF, or has entered something that is not a number (eg ABC ).因此,我们决定在scanf返回除 1 以外的任何值时停止循环(这意味着用户按下Ctrl + D触发了 EOF,或者输入了非数字的内容(例如ABC )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM