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

原文链接: https://www.cnblogs.com/jmhwsrr/p/14587105.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/209088

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午11:42
下一篇 2023年2月12日 下午11:43

相关推荐