getline시 개행 문자로 인해 발생하는 문제 해결

getline은 공백을 포함해서 문자열을 입력받고 싶을때 종종 쓰인다.

하지만 getline을 하는 시점에, stdin에 개행문자가 남아 있다면 문제가 종종 발생한다.


아래의 코드를 보자

  • n개의 공백을 포함하는 문자열을 vector<vector> 에 넣고 싶다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main() {
	int n;	cin >> n;
	string str;
	vector<string> vec;

	while (n--) {
		getline(cin, str);
		vec.push_back(str);
	}

	cout << "-----print start----\n";
	for (string it : vec) {
		cout << it << "\n";
	}
	return 0;
}

want input

1
2
3
2
a b c
c d f

want output

1
2
3
-----print start----
a b c
c d f

real input

1
2
2
a b c

real output

1
2
3
-----print start----

a b c

2를 입력할때 남은 \n (개행 문자) 때문에, 첫번째 getline에서 \n만 받아 버린것을 확인할 수 있다.

  • 이 문제는 남은 \n 을 지워 줌으로써 해결 할 수 있다.

    stdin 버퍼에 남은 \ncin.ignore()을 이용해 지워 준다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main() {
	int n;	cin >> n;
	cin.ignore();	//개행문자 삭제
	string str;
	vector<string> vec;

	while (n--) {
		getline(cin, str);
		vec.push_back(str);
	}

	cout << "-----print start----\n";
	for (string it : vec) {
		cout << it << "\n";
	}
	return 0;
}