本文主要是介绍C++之stringstream类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、介绍
<sstream> 定义了三个类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作, stringstream 主要用来进行数据类型转换。由于 stringstream 使用 string 对象来代替字符数组(snprintf方式),可以避免缓冲区溢出的危险;而且,因为传入参数和目标对象的类型会被自动推导出来,所以不存在错误的格式化符的问题。
二、stringstream分割字符串
2.1 如果是空格,可以直接分割
#include <string>
#include <sstream>
#include <iostream>using namespace std;int main()
{string str = "i am a boy";stringstream is(str);string s;while (is >> s) { // 输出流cout << s << endl;}system("pause");return 0;
}
2.2 如果输入的字符串要分别输出的话,必须使用 sstream.str("")来清空 stringstream
stringstream sstream;int first, second;// 插入字符串sstream << "456"; // 转换为int类型sstream >> first;cout << first << endl;// 清空 sstreamsstream.str("") //等价于sstream.str(std::string());sstream.clear(); // 清除eofbit标志位// 插入bool值sstream << true; // 转换为int类型sstream >> second;cout << second << endl;
三、字符串的拼接
stringstream 中存放多个字符串,实现多个字符串拼接
#include <string>
#include <sstream>
#include <iostream>using namespace std;int main() {stringstream sstream;// 将多个字符串放入 sstream 中cout << "开始拼接" << endl;sstream << "first" << " " << "string,";sstream << " second string";cout << "最后的结果 is: " << sstream.str() << endl;cout << "清空 sstream" << endl;sstream.str("");sstream << "third string";cout << "After clear, 最后的结果 is: " << sstream.str() << endlreturn 0;
}
四、实现任意类型的转换
示例代码,介绍将 string 类型转换为 int 类型过程。
#include <string>
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <string> template<typename out_type, typename in_value>
out_type convert(const in_value & t) {stringstream stream;stream << t;//向流中传值out_type result;//这里存储转换结果stream >> result;//向result中写入值return result;
}int main() {string str = "1 23 # 4";stringstream ss;ss << str; // 输入流while (ss >> str) { // 输出流cout <<"原字符串"<< str << endl;int val = convert<int>(str);cout << "转化后的值" << val << endl;}return 0;
}
参考:
C++编程语言中stringstream类介绍_liitdar的博客-CSDN博客_stringstream
c++ stringstream(老好用了)_龙贝尔莱利的博客-CSDN博客_c++ stringstream
这篇关于C++之stringstream类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!