{ }codelper
读到输入结束求和P0018

一直加到结束

每行给出一个整数,但不告诉你一共有几行。
读入所有数直到输入结束,输出它们的和。
输入至少有一行,没有空行。
最后一行末尾可能有换行,也可能没有。

输入
行数 1~100,000,-10,000 ≤ 每个数 ≤ 10,000
输出
一行和
样例 1 · stdin
3
-1
10
stdout
12
样例 2 · stdin
5
stdout
5
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

察觉“输入结束了”的方法因语言而异。
Python for line in sys.stdin:(结束时循环自动停止——一直调用 input() 会抛出 EOFError),Java BufferedReader.readLine() 和 C# Console.ReadLine() 在结束时返回 null,C while (scanf("%d", &x) == 1)(结束时 scanf 返回 EOF),C++ while (std::cin >> x),JS/TS 一次读入全部输入再拆分即可。
Craykon 的 控制台.读行() 在结束时返回 空,所以用 当 (行 != 空) 循环。
C 的经典陷阱是 while (!feof(stdin))——feof 要在读取*失败之后*才变为真,所以最后一个换行之后 scanf 失败了,留下的 x 又被加了一次(第一个样例得到 22 而不是 12)。
不要像前面的题那样把第一行当作个数来读。

Pythonmain.py · 6 行
import sys total = 0for line in sys.stdin:  # 입력이 끝나면 반복도 끝난다    total += int(line)print(total)
JavaScriptmain.js · 2 行
const nums = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);console.log(nums.reduce((s, x) => s + x, 0));
TypeScriptmain.ts · 3 行
import { readFileSync } from "node:fs";const nums: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);console.log(nums.reduce((s, x) => s + x, 0));
JavaMain.java · 13 行
import java.io.BufferedReader;import java.io.InputStreamReader; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        int total = 0;        String line;        // readLine()은 입력이 끝나면 null        while ((line = br.readLine()) != null) total += Integer.parseInt(line.trim());        System.out.println(total);    }}
C#Main.cs · 13 行
using System; class Program{    static void Main()    {        int total = 0;        string line;        // ReadLine()은 입력이 끝나면 null        while ((line = Console.ReadLine()) != null) total += int.Parse(line);        Console.WriteLine(total);    }}
C++main.cpp · 9 行
#include <iostream> int main() {    std::ios::sync_with_stdio(false);    std::cin.tie(nullptr);    int x, total = 0;    while (std::cin >> x) total += x; // 읽기에 실패하면(입력 끝) 거짓    std::cout << total << '\n';}
Cmain.c · 9 行
#include <stdio.h> int main(void) {    int x, total = 0;    /* scanf는 수를 읽은 개수를 돌려준다 — 입력이 끝나면 EOF(-1)라 1이 아니다 */    while (scanf("%d", &x) == 1) total += x;    printf("%d\n", total);    return 0;}
Craykonmain.cray · 8 行
합 = 0;줄 = 控制台.读行();当 (줄 != 空){    합 += 줄.转数字();    줄 = 控制台.读行();}控制台.输出(합);