끝까지 더하기
한 줄에 정수가 하나씩 주어지는데, 몇 줄인지는 알려 주지 않는다.
입력이 끝날 때까지 모든 수를 읽어 합을 출력하라.
입력에는 적어도 한 줄이 있고, 빈 줄은 없다.
마지막 줄 끝에는 줄바꿈이 있을 수도 없을 수도 있다.
- 입력
- 줄 수 1 ~ 100,000, -10,000 ≤ 각 수 ≤ 10,000
- 출력
- 합 한 줄
3 -1 10
12
5
5
한 줄에 정수가 하나씩 주어지는데, 몇 줄인지는 알려 주지 않는다.
입력이 끝날 때까지 모든 수를 읽어 합을 출력하라.
입력에는 적어도 한 줄이 있고, 빈 줄은 없다.
마지막 줄 끝에는 줄바꿈이 있을 수도 없을 수도 있다.
3 -1 10
12
5
5
실행하면 이 줄들이 차례로 input()·표준 입력으로 들어가요(실행 중에 묻지 않아요).
$ 준비됐어요
코드를 입력해 풀려면 PC에서 열어 주세요. 모바일에서는 문제와 풀이를 볼 수 있어요.
"입력이 끝났다"를 알아차리는 방법이 언어마다 달라요.
Python for line in sys.stdin:(끝나면 반복이 멈춤 — input()을 계속 부르면 EOFError), Java BufferedReader.readLine()과 C# Console.ReadLine()은 끝나면 null, C while (scanf("%d", &x) == 1)(끝나면 EOF를 돌려줌), C++ while (std::cin >> x), JS·TS는 입력 전체를 한 번에 읽어 나누면 돼요.
크레이콘은 콘솔.줄읽기()가 끝에서 빈값을 돌려줘서 동안 (줄 != 빈값)으로 돌아요.
C의 고전 함정은 while (!feof(stdin))이에요 — feof는 읽기가 실패한 *뒤에야* 참이 돼서, 마지막 줄바꿈 다음의 실패한 scanf 뒤에 남은 x를 한 번 더 더해요(첫 예시가 12가 아니라 22).
앞의 문제처럼 첫 줄을 개수로 읽으면 안 돼요.
import sys total = 0for line in sys.stdin: # 입력이 끝나면 반복도 끝난다 total += int(line)print(total)const nums = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);console.log(nums.reduce((s, x) => s + x, 0));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));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); }}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); }}#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';}#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;}합 = 0;줄 = 콘솔.줄읽기();동안 (줄 != 빈값){ 합 += 줄.수로변환(); 줄 = 콘솔.줄읽기();}콘솔.쓰기(합);