C ++中的Stringstream
在这里,我们将看到C++中的字符串流。字符串流将字符串对象与字符串关联。使用此方法,我们可以从字符串中读取内容,就像是像cin这样的流一样。
Stringstream有不同的方法。这些如下-
clear():用于清除流
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) {
//在此处为tmp提供适当的检查,例如是否为空
//同时剥离下来的符号一样,等!?
//最后推一下。
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