작성 이유
자바스크립트를 사용하여 백준 문제를 풀려고 하다보니 어떻게 테스트 케이스를 입력받는지 알 수 없어 당황했다. 아래 2가지 방법을 주로 사용한다고 하니 공부 차원에서 정리한다.
백준 입력 방법
1. fs 모듈 사용
fs 모듈 (File System module)은 파일 처리와 관련된 전반적인 작업을 하는 모듈. readline으로 받아보는 속도보다 빠르고 백준에서 권장되는 방법
/* input : a b */
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split(' ');
console.log(input); // [ 'a', 'b' ]
/** input :
* a
* b
*/
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
console.log(input); // [ 'a', 'b' ]
2. readline 모듈 사용
2-1. 한줄 입력받기
/* 한 줄 입력받기 */
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
});
let input = [];
readline.on('line', function(line) {
// 입력받은 값은 line에 저장
console.log(line);
readline.close();
}).on('close', function(){
// 입력이 끝난 후 수행할 코드 입력
process.exit();
});
2-2. 공백 기준으로 입력받기
/* 공백 기준 입력받기 */
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
});
let input = [];
readline.on('line', function(line) {
input = line.split(' ').map(el => parseInt(el));
// 문자열을 저장하고 싶으면 map함수 제외
readline.close();
}).on('close', function(){
console.log(input);
process.exit();
});
2-3. 여러 줄 입력받기
/* 여러 줄 입력받기 */
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
});
let input = [];
readline.on('line', function(line) {
input.push(line);
// 입력 종료 시 ctrl+c
}).on('close', function(){
console.log(input);
process.exit();
});
'🤜 코테' 카테고리의 다른 글
백준 문제 풀이 : 스택 (10828) (0) | 2024.05.08 |
---|---|
백준 문제 풀이 : 괄호 (9012) (0) | 2024.05.08 |
210324 코테공부 (0) | 2021.03.24 |
프로그래머스 Lv1. 모의고사 (Java) (0) | 2021.03.23 |
210323_TODAY SQL (0) | 2021.03.23 |