-
[C++] string 공백 포함 입력, 입력 버퍼 비우기공부/C, C++ 2022. 1. 31. 02:20
#include <iostream> #include <string> using namespace std; int N; string input; int main(void) { cin >> N; cin.ignore(); while(N--) { cout << "[" << N << "]\n"; getline(cin, input); } return 0; }
cin.ignore( )
입력 버퍼를 비워주는 함수.
cin.ignore( ) 를 추가하지 않았을때는 N번이 아닌 (N-1)번의 입력을 받은 후 프로그램이 종료되었음!
(주의) cin.ignore( )는 입력 버퍼의 첫번째 문자를 비워준다.
위 코드에서는 cin >> N; 을 통해 숫자를 받은 후 엔터(\n)를 입력하므로 입력 버퍼에 \n이 남아있는 상태인데, cin.ignore( )을 이용해서 \n을 지워줬으므로 입력 버퍼가 지워진 것이다.
아래 코드를 통해 cin.ignore( )을 실험해봤다.
#include <iostream> #include <string> using namespace std; int N; string input; int main(void) { cin >> N; cin.ignore(3); while(N--) { cout << "[" << N << "]\n"; getline(cin, input); cout << ">> " << input << "\n"; } return 0; }
코드 실행 결과
1 입력 후 엔터 👉 입력 버퍼: ['\n']
cin.ignore(3) 👉 입력 버퍼: [ ] // '\n'은 삭제되었고, cin에 입력될 문자열의 처음 2개의 문자를 삭제함
"abcdefg hijk" 입력 👉 입력 버퍼: ['cdefg hijk']
getline(std::cin, string str)
공백을 포함한 문자열을 입력으로 받게하는 함수
❗ 틀린 부분이 있을 수 있습니다... cin이랑 getline에 대해서는 더 찾아봐야될 것 같다
'공부 > C, C++' 카테고리의 다른 글
[C/C++] long long 데이터 형의 shift 연산 수행 (0) 2022.05.03 [C++] 공백으로 문자열 자르기, for each문 (나중에 포스트 하기) (0) 2022.03.18 [C++] sort( )를 이용한 구조체 정렬 (0) 2022.01.12 [C++] vector에 원소 추가하기 (0) 2021.10.10 [C++] struct형의 vector를 함수 인자로 넘기기 (0) 2021.10.08