C++ 开发,将数值转换为字符串问题,不能直接拼接引号
#include <iostream>
#include <string>using namespace std;...int num = 42;string str = num + "";cout << str << endl;
- 在 C++ 开发中,上述将数值转换成字符串的方式是错误的
问题原因
-
num 是一个数值类型,而
""
是一个字符串字面量,即const char*
类型 -
num + ""
中,会将""
隐式转换为整数,因为+
运算符的两个操作数需要类型一致 -
这会导致指针算术运算,将
num
加到字符串地址上,这是无意义的且危险的 -
如果
num
是浮点类型,这种写法直接无法编译
#include <iostream>
#include <string>using namespace std;...double num = 1.1;string str = num + "";cout << str << endl;
# 输出结果E2138 表达式必须具有算术或未区分范围的枚举类型
C2111 “+”: 指针加法要求整型操作数
处理策略
- 使用
to_string
方法
#include <iostream>
#include <string>using namespace std;...int num = 42;string str = to_string(num);cout << str << endl;
- 使用字符串流
#include <iostream>
#include <string>
#include <sstream>using namespace std;...int num = 42;ostringstream oss;
oss << num;
string str = oss.str();cout << str << endl;