C++中string类字符串和数字的转换

C++中 string类字符串和数字的转化有简便方法:

头文件  中有两个类:

  1. istringstream——字符串输入流
  2. ostringstream——字符串输出流

能够很便捷的实现string类字符串和数字的转换。

同时要用到 >>  和 <<

  1. >> 从输入流读取一个string。
  2. << 把一个string写入输出流。

string 字符串 ==》数字:

istringstream zxc ("520.1");    //定义对象iss,同时初始化为  
//其实就是:    istringstream zxc;    zxc.str("123.5");                 
                
double num;
 
zxc>>num;             
cout<

结果就是:520.1


最常见的:

string str="520.1";
 
double num;
 
istringstream(str)>> num; 
cout<< num << endl;

数字string ==》字符串 :

ostringstream zxc;
zxc << 520.1;                   //相当于调用: oss.str("123.5");
string str = zxc.str();
cout<< str << endl;

结果是:520.1,但是是字符串类型,也就是 "520.1"

你可能感兴趣的:(C++)