zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++之stringstream(字符串与数字相互转换)(七十四)

C++转换 字符串 数字 相互
2023-09-14 09:09:57 时间

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类型转为字符串,放入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; 
}