下面是将整数转换为字符串的代码,我试图不为此使用C ++内置函数,但是我的代码未产生任何输出。
int main(){
int a;
string b;
cin>>a;
while(a){
b+=(a%10);
a/=10;
}
cout<<b;
return 0;
}
输入-
789
预期产出
987
但我没有任何答案。
附言:我已经在代码中使用了所有必需的头文件。
最佳答案
您不能将int
添加到string
(或者在这种情况下不应该)。您需要to_string
将int转换为字符串,以便+=
运算符充当串联:
#include <iostream>
#include <string>
using namespace std;
int main(){
int a;
string b;
cin>>a;
while(a){
b+=std::to_string(a%10);
a/=10;
}
cout<<b;
return 0;
}
Demo
发生了什么事?
std::string
具有一个operator+=
,可以快速连接。您可以串联另一个字符串或字符。通过重载选择哪个版本的串联。当您尝试使用string += int
时,选择了char
重载(int
转换为char
),因此随机垃圾被附加到了字符串上,而不是您想要的。关于c++ - 无法将整数写入字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45774185/