파게로그

[백준 10951번] 입력 개수가 미정일 때 본문

콤퓨타 왕왕기초/PS

[백준 10951번] 입력 개수가 미정일 때

파게 2020. 10. 25. 18:01

문제 링크: 10951번 A+B - 4

https://www.acmicpc.net/problem/10951

 

C++의 경우, 테스트 케이스의 개수가 주어지지 않는 경우, cin.eof()를 이용하여 입력을 중단시킬 수 있다.

자바는 bufferedReader.readLine( )의 반환값이 null일 때 입력받기를 중단한다. Scanner를 이용할 경우에는 .hasNext( ) 메서드를 이용할 수 있다.

 

C++

아래와 같이 .eof( )를 이용할 수 있다.

#include <iostream> using namespace std; int main(void) { ​​​​while (1) { ​​​​​​​​int a, b; ​​​​​​​​cin >> a >> b; ​​​​​​​​if (cin.eof()) break; // cin.eof() returns true if eof ​​​​​​​​cout << a+b << '\n'; ​​​​} ​​​​return 0; }

 

아래와 같이 보다 간결하게 작성할 수 있다.

 

#include <iostream> using namespace std; int main() { int a, b; while (cin >> a >> b) { ‌‌cout << a + b << '\n'; } return 0; }

 

Java

BufferedReader 이용

import java.io.*; import java.util.*; public class Main { ​​​​public static void main(String[] args) throws IOException { ​​​​​​​​BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); ​​​​​​​​StringBuilder sb = new StringBuilder(); ​​​​​​​​String line; ​​​​​​​​while ((line = br.readLine()) != null) { ​​​​​​​​​​​​StringTokenizer st = new StringTokenizer(line, " "); ​​​​​​​​​​​​int a = Integer.parseInt(st.nextToken()); ​​​​​​​​​​​​int b = Integer.parseInt(st.nextToken()); ​​​​​​​​​​​​sb.append(a+b).append('\n'); ​​​​​​​​} ​​​​​​​​System.out.print(sb); ​​​​} }

 

Scanner 이용

import java.util.Scanner; public class Main { ​​​​public static void solution() { ​​​​​​​​Scanner sc = new Scanner(System.in); ​​​​​​​​while (sc.hasNext()) { ​​​​​​​​​​​​int a = sc.nextInt(); ​​​​​​​​​​​​int b = sc.nextInt(); ​​​​​​​​​​​​System.out.println(a+b); ​​​​​​​​} ​​​​​​​​sc.close(); ​​​​} ​​​​ ​​​​public static void main(String[] args) { ​​​​​​​​solution(); ​​​​} }

 

Python

파이썬으로 PS를 제대로 해보지 않아서 잘 모르겠지만, 여러 코드를 살펴본 바 아래 코드 정도가 가장 정석적인 것이 아닐까 한다.

from sys import stdin for line in stdin: ​​​​print(sum(map(int, line.split())))