本文主要是介绍C++之stringstream(字符串与数字相互转换)(七十四),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.代码示例
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类型转为字符串,放入bufcout << "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;
}
这篇关于C++之stringstream(字符串与数字相互转换)(七十四)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!