basic_string_operator_ltltgtgt
basic_string_operator_ltltgtgt (basic_string 스트림 삽입/추출 연산자)
이 페이지에서는 std::basic_string에 대한 스트림 삽입 연산자(operator<<)와 추출 연산자(operator>>)를 다룬답니다. 이 연산자들은 문자열을 출력 스트림에 쓰거나 입력 스트림에서 읽을 때 사용되며, C++ 표준 라이브러리의 <string> 헤더에 정의되어 있어요.
출처: cppreference
본문
헤더 <string>에 정의됨 |
||
|---|---|---|
template < class CharT , class Traits , class Allocator > std :: basic_ostream < CharT , Traits >& operator << ( std :: basic_ostream < CharT , Traits >& os , const std :: basic_string < CharT , Traits , Allocator >& str ); |
(1) | |
template < class CharT , class Traits , class Allocator > std :: basic_istream < CharT , Traits >& operator >> ( std :: basic_istream < CharT , Traits >& is , std :: basic_string < CharT , Traits , Allocator >& str ); |
(2) |
(1) 연산자는 결과 시퀀스 seq(즉, str의 내용에 패딩을 더한 것)의 각 문자를 출력 스트림 os에 마치 os . rdbuf () -> sputn ( seq , n )을 호출하는 것처럼 삽입해요. 여기서 n은 std :: max ( os . width (), str . size ())예요. 마지막으로 os . width ( 0 )을 호출하여 std::setw의 효과를 취소해요.
return os << std :: basic_string_view < CharT , Traits > ( str ); 와 동일 |
(C++17부터) |
|---|
(2) 연산자는 다음 조건 중 하나가 발생할 때까지 입력 스트림 is에서 문자를 추출해요:
is . width () > 0이면N은is . width ()이고, 그렇지 않으면N은str . max_size ()인데,N개의 문자가 읽혀요.- 스트림
is에서 파일 끝(end-of-file) 조건이 발생해요. is의 다음 문자c에 대해std :: isspace ( c , is . getloc ())가 참이에요 (이 공백 문자는 입력 스트림에 남아 있어요).
문자가 하나도 추출되지 않으면 is에 std::ios::failbit가 설정되며, 이로 인해 std::ios_base::failure가 발생할 수 있어요.
예외 (Exceptions)
매개변수 (Parameters)
os |
- | 문자 출력 스트림 |
|---|---|---|
is |
- | 문자 입력 스트림 |
str |
- | 삽입되거나 추출될 문자열 |
반환값 (Return value)
예제 (Example)
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string greeting = "Hello, whirled!";
std::istringstream iss(greeting);
std::string hello_comma, whirled, word;
iss >> hello_comma;
iss >> whirled;
std::cout << greeting << '\n'
<< hello_comma << '\n' << whirled << '\n';
// Reset the stream
iss.clear();
iss.seekg(0);
while (iss >> word)
std::cout << '+' << word << '\n';
}
출력:
Hello, whirled!
Hello,
whirled!
+Hello,
+whirled!
결함 보고서 (Defect reports)
다음 동작 변경 결함 보고서는 이전에 발표된 C++ 표준에 소급 적용되었어요.
| DR | 적용 대상 | 발표된 동작 | 올바른 동작 |
|---|---|---|---|
| LWG 25 | C++98 | n은 os . width ()와 str . size () 중 더 작은 값이었음 |
n은 둘 중 더 큰 값임 |
| LWG 90 | C++98 | 공백 확인에 std :: isspace ( c , getloc ())가 사용되었지만 getloc은 <string>에 선언되어 있지 않음 |
getloc ()을 is . getloc ()로 대체함 |
| LWG 91 | C++98 | operator>>가 FormattedInputFunction처럼 동작하지 않았음 |
FormattedInputFunction처럼 동작함 |
| LWG 211 | C++98 | 문자가 추출되지 않아도 failbit를 설정하지 않았음 |
failbit를 설정함 |
| LWG 435 | C++98 | os . rdbuf () -> sputn ( str . data (), n )으로 문자를 삽입했으며, LWG 25의 해결로 os . width ()가 str . size ()보다 크면 동작이 정의되지 않았음 |
패딩을 먼저 결정하고 패딩된 문자 시퀀스를 대신 삽입함 |
| LWG 586 | C++98 | operator<<가 FormattedOutputFunction처럼 동작하지 않았음 |
FormattedOutputFunction처럼 동작함 |
같이 보기 (See also)
operator<< (C++17) |
문자열 뷰에 대한 스트림 출력을 수행해요 (함수 템플릿) [편집] |
|---|