将数字转换成字符

我想要一个反向整数值

代码

int number=123,num1,num2,num3;
num1=每100个数字;
num2=数量%100/10;
num3=数量%10;
静态_cast<char>(num1、num2、num3);
库特&lt&书信电报;num3+num2+num1&lt&书信电报;endl;

结果是6..(我想《321》出来。)

我的代码有什么问题

问题:

即使使用static\u cast<将int转换为char;char&gt,它将保留其值。此外,这不是您所称的static\u cast<char&gt

解决方案:

如果您只想使用您的方法打印它们,您甚至不必将数字转换为char。只需利用打印即可&lt&lt操作员

\include<iostream>
int main(){
整数=123,num1,num2,num3;
num1=每100个数字;
num2=数量%100/10;
num3=数量%10;
标准::cout<<num3<<num2<<num1<<标准::endl;
}

但是,这仅适用于100到999之间的数字

更好的解决方案是将数字转换为std::string,并使用std::reverse将其从<算法&gt标题

\include<iostream>
#包括<算法>
int main(){
整数=123;
std=string(std=u::str);
反向(str.begin(),str.end());
标准::cout<<str<<标准::endl;
}

然后,如果您想将反转的数字作为整数而不是打印它,可以使用std::stoi

\include<iostream>
#包括<算法>
int main(){
整数=123;
std::string str=std::to_字符串(数字);
反向(str.begin(),str.end());
整数=标准::stoi(str);
标准::cout<<反向编号<<标准::endl;
}

请注意,这将不起作用,并且由于前导'-'而引发负数异常

发表评论