文章参考菜鸟教程
sstream 提供了一种方便的方式用来处理字符串流(像处理流一样处理字符串)
分为 3 类:
istringstream
:从字符串中读取数据
ostringstream
:将数据写入字符串
stringstream
:上面二者的结合,可同时进行读取和写入
# istringstream
从字符串读取数据:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include <iostream> #include <sstream> using namespace std;
int main() { string data = "10, 20.5"; istringstream iss(data); int i; double d; iss >> i >> d; cout << i << " " << d; return 0; }
|
# ostringstream
向字符串中写入数据:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include <iostream> #include <sstream> using namespace std;
int main() { int i = 10; double d = 20.5; ostringstream oss; oss << i << " " << d; string result = oss.str(); cout << result; return 0; }
|
# stringstream
# 类型转换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #include <sstream> #include <iostream> using namespace std;
template<class T> void to_string(string& result, const T& t) { ostringstream oss; oss << t; result = oss.str(); }
int main() { string s1, s2, s3; to_string(s1, 10.5); to_string(s2, 123); to_string(s3, true); cout << s1 << '\n' << s2 << '\n' << s3; return 0; }
|
# 字符串的拼接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| #include <string> #include <sstream> #include <iostream> using namespace std; int main() { stringstream sstream; sstream << "first" << " " << "string,"; sstream << " second string"; cout << "strResult is: " << sstream.str() << endl; sstream.str(""); sstream << "third string"; cout << "After clear, strResult is: " << sstream.str() << endl;
return 0; }
|
# 清空
在多次使用类型转换之前必须使用 clear (),不能使用 str ("")
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| #include <sstream> #include <iostream> using namespace std; int main() { stringstream sstream; int first, second; sstream << "456"; sstream >> first; cout << first << endl; sstream.clear(); sstream << true; sstream >> second; cout << second << endl; return 0; }
|
# clear() && str("")
-
**str ():**str () 用于 << ,将字符串替换成 str 中的内容,并且从起始位置开始书写;可以用于字符串的清空和初始化
-
**clear ():**clear () 用于 >>,用来删除文件的结束标志,使 << 可以继续追加(多用于连续的类型转换)
# str()
![]()
-
通过 s 可以看出,<< 每次都在结尾追加
-
通过 s1 可以看出,str ("") 可以清空字符串
-
通过 s2 可以看出,使用 str 可以清空并重新设置字符串,并将 “鼠标” 移到字符串开头,从开头开始追加
-
通过 s3 可以看出 clear 对 << 无用
# clear()
![]()
![]()
- 通过 s2 可知,类型转换之后遇到文件结尾,无法继续 << 向后追加
- 通过 s3 可知,如果字符串后面有空格或者换行,则不是遇到文件尾结束,可以继续向后追加
- 通过 s4 可知,添加了 clear () 之后,删除了文件结束标志,可以继续追加;并且每次的类型转换会记下结束的位置,下次从结束的位置开始接着类型转换