教科书中很少会提到string与int或是float的相互转换,但是在实际工程中会经常遇到,尤其在做UI控件显示的时候。比如说你要在edit控件中显示一个数值,那你就需要把这个数值首先转为string,然后再将这个string付给edit控件。
网上你会找到很多的转换方法,个人觉得效率差不多的情况下,简洁最好。
这里主要用到的是stringstreams:
stringstream 是 C++ 提供的另一个字串型的串流(stream)物件,和之前学过的 iostream、fstream 有类似的操作方式。要使用 stringstream, 必須先加入這一行:
#include <sstream>
stringstream 主要是用在將一個字串分割,可以先用 clear( )以及 str( ) 將指定字串設定成一开始的內容,再用 >> 把个別的资料输出,例如:
下面就言归正传。
1、stringstreams中number to string
主要是两步走:
把number输出到stream
从stream中得到string
int Number = 123;
string Result;
ostringstream convert;
convert << Number;
Result = convert.str();
可以将上述代码缩略成一句话:
int Number = 123;
string String = static_cast<ostringstream*>( &(ostringstream() << Number) )->str();
这里需要说明的是,number不限于int,float一样可以工作
2、stringstreams中string to number
同样需要两步走:
根据string构造一个stream
将value 读到变量中
string Text = "456";
int Result;
istringstream convert(Text);
if ( !(convert >> Result) )
{
Result = 0; //if that fails set 'Result' to 0
}
同样,也可以对上面的代码进行简化:
string Text = "456";
int Number;
if ( ! (istringstream(Text) >> Number) ) Number = 0;
3、C++11中number string互转
C++11为我们提供了更为便利的方法:
整型、浮点型转string
std::to_string
重载如下:
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
字符串转整型:
stoi, stol, stoll
字符串转浮点型:
stof, stod, stold
int number = 123;
string text = to_string(number);
text = "456"
number = stoi(number);
4、C - stdio中的string与number转换
Number to String
int Number = 123;
char Result[16];
sprintf ( Result, "%d", Number );
String to Number
char Text[] = "456";
int Result;
sscanf ( Text, "%d", &Result );
5、C - stdlib中的string与number转换
itoa
atoi
atol
atof
strtol
strtoul
strtod
但需要注意的是,上面的几个函数并非标准,尽量少用。
https://blog.csdn.net/wangshubo1989/article/details/50241899