C++에서 문자열을 사용하는 방법은 두 가지가 있다.
1. char 배열 사용
char str[5] = { 'a', 'b', 'c', 'd', 'e' };
이 방식은 C언어에서 쓰던 방식과 같다.
문자열 입력
cin으로 문자열을 입력받게 되면 띄어쓰기, tab, enter 단위로 잘라서 받기 때문에 공백을 포함한 문자열을 한번에 입력받을 수 없다.
#include <iostream>
int main() {
char arr[100];
std::cin >> arr;
std::cout << arr;
return 0;
}결과
따라서 공백을 포함한 문자열을 입력받을 때, cin.getline()함수를 사용한다.
#include <iostream>
int main() {
char arr[100];
std::cin.getline(arr, 100);
std::cout << arr;
return 0;
}
결과
iostream에 정의되어 있는 것을 보면, delimiter(구분문자)를 매개변수로 넘길 수 있으며 기본적으로는 \n(엔터)를 구분자로 처리한다는 것을 볼 수 있다.
basic_istream& __CLR_OR_THIS_CALL getline(_Elem *_Str, streamsize _Count)
{ // get up to _Count characters into NTCS, discard newline
return (getline(_Str, _Count, _Myios::widen('\n')));
}
basic_istream& __CLR_OR_THIS_CALL getline(_Elem *_Str,
streamsize _Count, _Elem _Delim)
{ // get up to _Count characters into NTCS, discard _Delim
//...
return (*this);
}
2. string 사용
C++에서는 string이라는 클래스를 사용할 수 있다.
string 클래스는 문자 길이에 제한이 없고, 표준 클래스이므로 주로 문자열을 사용할 때에는 배열보다는 string클래스를 사용한다.
string 클래스는 string 헤더파일에 선언되어 있어 아래 구문을 추가해야 한다.
#include <string>
문자열 입력
string 클래스의 경우, 문자열을 입력받을 때는 string파일의 getline()함수를 사용한다.
#include <iostream>
#include <string>
int main() {
std::string str;
getline(std::cin, str);
std::cout << str;
return 0;
}
결과
getline()함수가 선언되어 있는 string파일을 살펴보면, 아래와 같이 오버로딩되어 있는 것을 확인할 수 있다.
delimiter(구분문자)를 지정하지 않으면, 기본적으로 \n(엔터)로 구분되는 것도 확인이 가능하다.
template<class _elem,="" class="" _traits,="" _alloc=""> inline
basic_istream<_Elem, _Traits>& getline(
basic_istream<_Elem, _Traits>&& _Istr,
basic_string<_Elem, _Traits, _Alloc>& _Str,
const _Elem _Delim)
{ // get characters into string, discard delimiter
//...
return (_Istr);
}
template<class _elem,="" class="" _traits,="" _alloc=""> inline
basic_istream<_Elem, _Traits>& getline(
basic_istream<_Elem, _Traits>&& _Istr,
basic_string<_Elem, _Traits, _Alloc>& _Str)
{ // get characters into string, discard newline
return (getline(_Istr, _Str, _Istr.widen('\n')));
}
template<class _elem,="" class="" _traits,="" _alloc=""> inline
basic_istream<_Elem, _Traits>& getline(
basic_istream<_Elem, _Traits>& _Istr,
basic_string<_Elem, _Traits, _Alloc>& _Str,
const _Elem _Delim)
{ // get characters into string, discard delimiter
return (getline(_STD move(_Istr), _Str, _Delim));
}
template<class _elem,="" class="" _traits,="" _alloc=""> inline
basic_istream<_Elem, _Traits>& getline(
basic_istream<_Elem, _Traits>& _Istr,
basic_string<_Elem, _Traits, _Alloc>& _Str)
{ // get characters into string, discard newline
return (getline(_STD move(_Istr), _Str, _Istr.widen('\n')));
}'C++' 카테고리의 다른 글
| [C++] 이러한 피연산자와 일치하는 "<<" 연산자가 없습니다. (0) | 2019.05.19 |
|---|---|
| [C++] 생성자와 소멸자 (0) | 2019.03.13 |
| [C++] 정보은닉과 캡슐화 (0) | 2019.03.13 |
| [C++] 객체지향 프로그래밍 (0) | 2019.03.13 |
| [C++] 클래스 (0) | 2019.03.08 |