我对以下代码提出了一个简单的问题
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
,
答案 0 :(得分:1)
您可以执行以下操作:
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]);
}
答案 1 :(得分:1)
这可能就足够了。
string convertInt(int number)
{
if (number == 0)
return "0";
string temp="";
string returnvalue="";
while (number>0)
{
temp+=number%10+'0';
number/=10;
}
for (int i=0;i<temp.length();i++)
returnvalue+=temp[temp.length()-i-1];
return returnvalue;
}
(我没有写这个函数,但通过quick Google search找到它。原帖is here。)
此函数的工作原理是将数字除以10.它取除除法的余数,它始终在0到9之间。然后通过添加字符{{的整数值“找到”表示该数字的字符。 1}}到它。
接下来,它取该除法的商,并一次又一次地执行相同的操作,直到商为零。
这会产生一个字符串,其中包含表示数字的字符,但顺序相反。最后一个循环在返回之前反转字符串。
正如克里斯在下面的评论中指出的那样,数字0到9保证按顺序排列
N3485,§2.3[lex.charset] / 3:在源和执行基础中 字符集,上面列表中0之后的每个字符的值 十进制数字应大于前一个值。 (上面的列表非常直观地说是0 1 2 3 4 5 6 7 8 9)。
以下是关于字符串操作的好阅读材料:The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
答案 2 :(得分:0)
在任何数字基础上手动格式化整数并不难。例如。在基地10:
void print(int n)
{
if (n == 0) { std::cout << '0'; return; }
if (n < 0) { std::cout << '-'; n = -n; }
std::string buf;
while (n != 0) { buf += '0' + n % 10; n /= 10; }
for (auto it = buf.rbegin(); it != buf.rend(); ++it)
std::cout << *it;
}
如果你的数字基数大于10,你必须提供一个合适的字母表并使用n % base
来枚举所需的数字。
如果要避免重新分配,可以在字符串中保留容量,并且可以通过采用n
的适当对数来计算所需容量。
答案 3 :(得分:0)
如果你真的必须自己提取数字
std::string manual_convert(int value)
{
if (x < 0)
return std::string("-") + manual_convert(-x); // handle negative values (except potentially INT_MIN)
else if (x == 0)
return "0";
std::string retval;
while (x > 0)
{
char digit = x%10 + '0'; // extract the proverbial digit
retval.append(1, digit);
x /= 10; // drop the digit, and prepare for next one
}
std::reverse(retval.begin(), retval.end()); // loop above extracted digits in reverse order
return retval;
}
答案 4 :(得分:0)
两种简单的方法:
#include <sstream>
string intToString(int x)
{
stringstream stream;
stream << x;
return stream.str();
}
或者如果您使用boost库
string str = lexical_cast<string>(x)