我有一个关于以下代码的快速问题
int main()
{
string data;
int x;
cin >> x;
if (x < 0)
{
data = to_string(x);
}
else
{
data = to_string(x);
}
return 0;
}
如果我不想使用to_string(x)
,而是想手动做一些事情。无论如何我可以做到吗?如果我使用 data = x;
这显然行不通。
附言。我也不想使用 atoi
,
最佳答案
您可以执行以下操作:
int main(){
int x;
cin>>x;
string s = ""; // s will represent x but with the digits reversed
bool neg = 0; // this flag is 1 if x is negative and 0 if positive.
// we will use it to find out if we should put a "-" before the number
if(x < 0){
neg = 1;
x *= -1; // making the number positive
}
while(x){
char c = '0' + x % 10; // c represent the least significant digit of x
s.push_back(c); // adding c to s
x /= 10; // removing the least significant digit of x
}
string ans = ""; // ans is our resulting string
if(neg) ans.push_back('-'); // adding a negative sign if x was negative
for(int i=s.size() - 1; i >= 0; i--) // adding the characters of s in reverse order
ans.push_back(s[i]);
}
关于c++ - 手动将整数变量放入字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29424726/