1.stringstream数字与字符串相互转换
#include <sstream>
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
int main()
{
stringstream stream;
string buf = "1234";
int i;
//1.字符串转换为整形
stream << buf;//插入字符串
stream >> i; //字符串转换成int类型
cout << "typeinfo(i) = " << typeid(i).name() << ", i = "<< i <<endl;
stream.clear();
//2.整形转字符串
int j = 1000;
stream << j;//将int流输入
stream >> buf;//将int类型转为字符串,放入buf
cout << "typeinfo(buf) = " << typeid(buf).name() << ", buf = "<< buf <<endl;
}
2.char* 与 int类型拼接
#include <sstream>
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
int main(){
stringstream stream;
int port = 1;
stream << "/dev/video" << port; //: /dev/video0
string str(stream.str());
cout <<"stream.str() = " << stream.str() <<endl;//: /dev/video0
cout <<"str = "<< str << endl;
cout <<"str.c_str() = " <<str.c_str() <<endl;
}
利用stringstream实现数字与字符串相互转换
最新推荐文章于 2023-02-22 19:45:14 发布