我对以下代码有一个快速的问题
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;
此方法显然将行不通。
ps。我不希望使用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]);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句