web/javascript prac with BOJ

[BOJ 1회독] 자바스크립트 입력 받기

xudegloss 2023. 3. 25. 02:42

방법 1. 외부 모듈 prompt-sync 이용하기

백준에서는 외부 모듈 사용이 불가능하기 때문에 돌아가지 않는다. 데이터를 입력받고 싶은 경우에 이용하기.

 

Step 1. npm을 이용하여  prompt-sync 모듈 설치하기.

npm install prompt-sync

설치를 하면 .json 파일이 2개가 생기는 것을 볼 수 있다.

 

Step 2. prompt-sync 모듈을 불러와서 원하는 데이터 입력받기.

// const prompt = require("prompt-sync")({ sigint: true });
// 모듈 불러와서 진행하는 것이기 때문에, 백준에서 돌아가지 않는다.

const prompt = require("prompt-sync")();
let [A, B] = prompt("두 수를 입력하세요 : ").split(" ");
console.log(Number(A) + Number(B));

방법 2. 내장 모듈 fs 이용하기

백준에서 사용 가능한 모듈이다. 리눅스인 경우와 아닌 경우로 조건을 나누어서 설정하면 된다.

  • fs module : 파일 처리와 관련된 전반적인 작업을 하는 모듈

 

Step 1. commonJS Modules 불러오기.

 

Step 2. 파일 경로를 리눅스인 경우에는 /dev/stdin 실행하고, 윈도우인 경우에는 /input.txt 가져오기. filePath라는 변수에 담아주기. node.js에서의 process.platform을 이용하면 된다. input.txt는 받아오고자 하는 데이터를 의미한다.

Step 3. readFileSync를 통하여 input 가져오기. 이 때 주의할 점은 __dirname + filePath를 적어줘야 한다. 그렇게 하지 않으면 경로 오류가 발생한다.

 

Step 4. 원하는 연산 진행하기. 

 

// 1. commonJS Modules 불러오기.
const fs = require("fs");

// 2. 파일 경로를 리눅스인 경우에는 /dev/stdin 실행하고, 윈도우인 경우에는 /input.txt 가져오기.
const filePath = process.platform === "linux" ? "/dev/stdin" : "/input.txt";

// 3. readFileSync를 통하여 input 가져오기.
let input = fs
  .readFileSync(__dirname + filePath)
  .toString()
  .split(" ");

console.log(input);

// 4. 원하는 연산 진행하기.
let A = parseInt(input[0]);
let B = parseInt(input[1]);
console.log(A - B);

 

[참고 블로그] fs.readFileSync 경로 오류 해결하기