본문 바로가기
C,C++

[C++] 공백이 포함된 문자열 입력받기(char array, string : getline)

by matters_ 2019. 10. 23.

C, C++에서 입력을 받을 때 "공백이 포함된 문자열"을 입력받는 법을 소개한다.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
using namespace std;
 
int main(){
 
    //string
    string str;
 
   getline(cin, str);
    //getline(cin, str, '\n');
 
    cout << "str: " << str << "\n";
 
    //char array
    char ch[100];
 
    cin.getline(ch, 100);
    //cin.getline(ch, 100, '\n');
 
    cout << "ch: " << ch << "\n";
 
    return 0;
}
cs

Result

std::getline (string)

istream& getline (istream& is, string& str, char delim);
istream& getline (istream& is, string& str);

<string> header file

첫 번째 인자 istream 객체 (키보드로 입력받는 경우 cin객체를 쓰면 된다.)

두 번째 인자 string 변수의 이름

세 번째 인자 delimitChar가 들어가게 되는데 생략이 가능하며 default로 '\n'가 들어간다.

 

즉, istream 객체(is)에서 character를 delimitChar(delim)를 만날때까지 읽어 string 변수(str)에 저장하는 의미이다.

 

 

이를 활용하면 delimitChar에 들어가는 인자를 ' '로 줘서 공백 기준으로 끊어 입력받는 code도 만들 수 있을 것이다.

getline(cin, str, ' ');

std::istream::getline

std::istream::getline
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

<istream> <iostream> header file

첫 번째 인자 char 배열의 포인터 s

두 번째 인자 char 배열에 저장될 최대 character의 개수 n

세 번째 인자 역시 delimitChar가 들어가게 되는데 생략이 가능하며 default로 '\n'가 들어간다.

 

cin 즉, C++ 표준 입출력 객체에서 character를 s 에 n-1개 만큼 읽는다는 말이다.

여기서 n-1개가 되는 이유는 '\0' 문자까지 포함시키기 때문

또한 중간에 delim으로 지정된 문자를 만난다면 delimitChar로 지정된 문자는 저장되지 않고 

cin버퍼에서도 사라지며 끝에 널문자('\0')가 덧붙여지고 종료된다.

다시말해 종료 조건이 2가지이다. n-1개의 char가 읽히는 경우, delim으로 지정된 문자를 만나는 경우

 

Reference

http://www.cplusplus.com/reference/string/string/getline/

https://lwww.cplusplus.com/reference/istream/istream/getline/

 

댓글