C++ 字符串与数字之间的转换

1. 数字转字符串

方法一

使用C++11标准新增的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);

测试:

int i = 100123;
double d = 100.123;
cout << to_string(i) << endl;
cout << to_string(d) << endl;

输出:

10123
100.123000

方法二

使用stringstream类:

template<typename out_type, typename in_value>
out_type convert(const in_value & t){
    stringstream stream;
    stream << t;//向流中传值
    out_type result;//这里存储转换结果
    stream >> result;//向result中写入值
    return result;
}

测试:

int i = 100123;
double d = 100.123;
cout << itos(i) << endl;
cout << dtos(d) << endl;

输出:

100123
100.123

2. 字符串转数字

字符串类提供了一系列的转换函数:

stoi    // Convert string to integer (function template )
stol    // Convert string to long int (function template )
stoul   // Convert string to unsigned integer (function template )
stoll   // Convert string to long long (function template )
stoull  // Convert string to unsigned long long (function template )
stof    // Convert string to float (function template )
stod    // Convert string to double (function template )
stold   // Convert string to long double (function template )

测试:

cout << stoi("123123") << endl;
cout << stod("123.123") << endl;

输出:

123123
123.123
posted @ 2021-03-27 21:39  刷书狂魔  阅读(902)  评论(0编辑  收藏  举报
总访问: counter for blog 次