C++ getline 공백 케이스 알아보기
Joonas' Note
C++ getline 공백 케이스 알아보기 본문
네임스페이스 std 아래에 있는 함수 getline은 한 줄 단위로 입력 받으며, 스페이스와 탭 등의 공백 문자들도 그대로 유지된다.
하지만 C++ 레퍼런스[1][2]에서는 공백에 대한 예제는 잘 나와있지 않아서 글로 남긴다.
아래 코드로 여러 케이스를 확인해보자.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
using namespace std; | |
int main() { | |
string s; | |
while(getline(cin, s)) { | |
cout << "^" << s << "$" << endl; | |
} | |
return 0; | |
} |
test-getline-input.txt에 적힌대로 입력하면, test-getline-output.txt와 같은 출력을 확인할 수 있다. ^는 문자열의 시작을, $는 문자열의 끝을 표시하기 위해 사용했다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
01234567890123456789 | |
ThisLineHaveNoSpace. | |
I have four spaces | |
ItHasTrailingSpace | |
<- Tab | |
----------- | |
--------- |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
^01234567890123456789$ | |
^ThisLineHaveNoSpace.$ | |
^I have four spaces$ | |
^ItHasTrailingSpace $ | |
^ <- Tab$ | |
^ -----------$ | |
^$ | |
^--------- $ |
공백 문자와 탭 문자가 포함된 문자열들, 심지어는 길이가 0인 문자열도 모두 잘 입력되는 걸 확인할 수 있다.
'개발 > C++' 카테고리의 다른 글
[C++ STL] binary_search, upper_bound, lower_bound 구현하기 (0) | 2020.03.19 |
---|---|
[C++ STL] sort 구현하기 (0) | 2020.03.19 |
Sublime Text 3에서 "프로시저 시작 지점" 오류 해결법 (0) | 2019.09.16 |
Chromium 빌드 (1) | 2019.05.07 |
MFC로 만든 미로 생성기 (0) | 2017.10.30 |