[C++] write string with ostream, stringstream class
Standard library에는 출력 가능한 모든 타입의 문자열을 만드는데 사용할 수 있는 stringstream을 class가 있습니다.
stringstream class의 str() method는 stream내부의 문자열을 return해 줍니다.
다음과 같이 ostream의 reference를 argument를 이용해 모든 종류의 output stream을 처리하는 method를 만들 수 있습니다.
Example 1
inputStringMethod라는 이름의 method를 만들었는데, 이 method는 ostream class type의 reference value를 인자로 받고 있습니다.
example 1번을 보시면 ostream class type의 reference value로 std::cout이 전달 하고 있습니다.
아래 링크를 보시면 우리가 쓰는 cout은 ostream class의 객체임을 알 수 있습니다. 그래서 inputStringMethod라는 method의 argument로 전달이 가능한 것입니다.
www.cplusplus.com/reference/iostream/cout/
Example 2
"D:\testFile.txt"라는 파일명을 이용하여 (files에서 동작하는) ofstream class의 개체를 생성합니다.
이 ofstream class의 객체를 그대로 argument로 전달 했는데, 이것도 ostream class type의 reference value로 처리가 가능합니다.
아래 link를 보시면 ofstream class는 ostream class의 하위 클래스임을 알 수 있습니다.
www.cplusplus.com/reference/ostream/ostream/?kw=ostream
Example 3
마지막으로 string stream을 이용하였습니다. stringstream은 strings을 위한 stream class입니다.
이 class의 객체는 string buffer를 사용하고 이 string buffer는 character들의 sequence를 담고 있습니다.
그리고 str이라는 member method를 이용하여 character들의 sequence에 직접 접근이 가능합니다.
최종 결과는 이것을 실행해 보면 cmd창과 d:\testFile.txt에 아래와 같이 출력됨을 확인할 수 있습니다.
>
'프로그래밍' 카테고리의 다른 글
[C++] shared_ptr, weak_ptr (0) | 2020.10.18 |
---|---|
[C++] unique_ptr (0) | 2020.10.17 |
[C++] string format (0) | 2020.10.12 |
[C++] File input/output (0) | 2020.10.11 |
Support C++ Standard in Visual Studio (0) | 2020.10.09 |