C++ 中 string 与其他类型 之间相互转换


写code 时  经常会遇到 输入串,  转换为 其他类型的数据

比如输入串123456 转换为 int 类型

笨方法就是扫描整个串 char -> int 然后 *10  操作,  这是非常麻烦的。

C++ 库中 提供了  一个很强大 流  sstream,  其中就有 sscanf 做格式输入

这里讲一个   很强大  istringsteam  和 ostringsteam


string 转换成 int, double, long long int

string -> int  string -> double string -> longlongint


string str;
int res;// double / long long int;
istringstream scin(str);  
scin >> res;  

 int, double, long long int 转换 成 string

string str;
int n;
ostringsteam tcin;
tcin<<n;
istringsteam scin(tcin.str());
scin >> str;


string  ->  char 

string -> char

string str;
char *ss = str.c_str();


posted @ 2018-05-19 22:22  Sizaif  阅读(594)  评论(0编辑  收藏  举报