getline은 공백을 포함해서 문자열을 입력받고 싶을때 종종 쓰인다.
하지만
getline
을 하는 시점에,stdin
에 개행문자가 남아 있다면 문제가 종종 발생한다.
아래의 코드를 보자
n
개의 공백을 포함하는 문자열을vector<vector>
에 넣고 싶다.
1 |
|
want input
1 |
|
want output
1 |
|
real input
1 |
|
real output
1 |
|
2를 입력할때 남은 \n (개행 문자)
때문에, 첫번째 getline
에서 \n
만 받아 버린것을 확인할 수 있다.
- 이 문제는 남은
\n
을 지워 줌으로써 해결 할 수 있다.stdin 버퍼에 남은
\n
을cin.ignore()
을 이용해 지워 준다.
1 |
|