여기서 우리는 C++의 문자열 스트림을 볼 것입니다. 문자열 스트림은 문자열 개체를 문자열과 연결합니다. 이것을 사용하여 문자열에서 마치 cin과 같은 스트림인 것처럼 읽을 수 있습니다.
Stringstream에는 다른 방법이 있습니다. 다음과 같습니다 -
지우기(): 스트림을 지우는 데 사용
str(): 스트림에 콘텐츠가 있는 문자열 개체를 가져오고 설정하려면
연산자 <<: 이것은 stringstream에 하나의 문자열을 추가합니다
연산자>> : stringstream 개체에서 읽는 데 사용됩니다.
문자열 스트림의 두 가지 예를 살펴보겠습니다. 첫 번째 프로그램에서는 단어를 별도의 문자열로 나눕니다.
예시
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
string str("Hello from the dark side");
string tmp; // A string to store the word on each iteration.
stringstream str_strm(str);
vector<string> words; // Create vector to hold our words
while (str_strm >> tmp) {
// Provide proper checks here for tmp like if empty
// Also strip down symbols like !, ., ?, etc.
// Finally push it.
words.push_back(tmp);
}
for(int i = 0; i<words.size(); i++)
cout << words[i] << endl;
} 출력
Hello from the dark side
여기서는 문자열 스트림을 사용하여 Decimal을 Hexadecimal로 변환합니다.
예시
#include<iostream>
#include<sstream>
using namespace std;
main(){
int decimal = 61;
stringstream my_ss;
my_ss << hex << decimal;
string res = my_ss.str();
cout << "The hexadecimal value of 61 is: " << res;
} 출력
The hexadecimal value of 61 is: 3d