stringstream
문자열을 마치 입력 스트림(cin)이나 출력 스트림(cout)처럼 사용할 수 있는 도구이다.
문자열 조작이 필요한 작업에서 매우 유용하다.
파싱: 문자열을 공백이나 특정 구분자를 기준으로 데이터를 분리
문자열 조합: 숫자와 문자열을 조합하여 하나의 문자열로 생성
*문자열 파싱(입력 스트림 역할)
#include <string>
#include <sstream> // stringstream 사용하기 위한 헤더
#include <iostream> // 스트림에 입,출력하기 위한 헤더
using namespace std;
int main()
{
// 기본적으로 공백을 기준으로 데이터를 나눔
string today = "2022 05 19";
int year, month, day;
stringstream ss(today);
ss >> year >> month >> day;
// 만약 '.' 과 같은 다른 문자로 데이터가 나눠져있다면
string today = "2022.05.19";
int year, month, day;
char dot1, dot2;
stringstream ss(today);
ss >> year >> dot1 >> month >> dot2 >> day;
return 0;
}
- today 문자열을 stringstream에 저장한 후, 기본적으로 공백을 기준으로 나눠 데이터를 저장하게 된다.
- 아래 상황과 같이 다른 문자로 데이터를 나눠져있다면, 그거에 맞게 char 타입으로 분기 문자를 저장해주면 된다.
*문자열 파싱(출력 스트림 역할)
#include <string>
#include <sstream> // stringstream 사용하기 위한 헤더
#include <iostream> // 스트림에 입,출력하기 위한 헤더
using namespace std;
int main()
{
int year = 2022, month = 5, day = 22;
stringstream ss;
ss << year << "." << month << "." << day;
return 0;
}
*주요 메서드
stringstream ss("123 ABC");
cout << ss.str() << endl; // 출력: 123 ABC
ss.str("New Data");
cout << ss.str() << endl; // 출력: New Data
ss.clear(); // 스트림 상태 초기화
str( ):
- 스트림의 내용을 문자열로 반환
str(const string&):
- 스트림의 내용을 새 문자열로 변경
Clear( ):
- 스트림의 상태를 초기화
'내배캠 > C++' 카테고리의 다른 글
온라인 학습 관리 시스템 구현 (0) | 2025.02.05 |
---|---|
피보나치 수열 (0) | 2025.02.04 |
디자인 패턴(Factory Pattern) (0) | 2025.01.20 |
Greedy 알고리즘 (0) | 2025.01.08 |
friend class (0) | 2025.01.07 |