C++ C++;:如何在不使用任何内置函数的情况下将字符串转换为整数
我正在尝试将字符串转换为整数,然后执行一些算术运算C++ C++;:如何在不使用任何内置函数的情况下将字符串转换为整数,c++,C++,我正在尝试将字符串转换为整数,然后执行一些算术运算 char string[10]; 如果字符串只有一个单词,我可以这样做: string[0]-'0' 如果字符串包含多个字符,如何将其转换为整数。最好使用内置函数,但如果要手动转换,则需要遍历字符串中实际为数字的所有字符。因为这是以10为基数,所以每次通过循环时,只需将累加器乘以10即可: int strToInt (const char *str) { int accumulator = 0; int sign = 1;
char string[10];
如果字符串只有一个单词,我可以这样做:
string[0]-'0'
如果字符串包含多个字符,如何将其转换为整数。最好使用内置函数,但如果要手动转换,则需要遍历字符串中实际为数字的所有字符。因为这是以10为基数,所以每次通过循环时,只需将累加器乘以10即可:
int strToInt (const char *str) {
int accumulator = 0;
int sign = 1;
if (*str == '-') {
str++;
sign = -1;
}
while (*str >= '0' && *str <= '9') {
accumulator *= 10;
accumulator += *str - '0';
str++;
}
return accumulator * sign;
}
int stroint(const char*str){
int累加器=0;
int符号=1;
如果(*str=='-'){
str++;
符号=-1;
}
而(*str>='0'&&*strinti,ans;
char num[]=“5678”;
int l=strlen(num);
ans=0;
对于(i=0;istd::stoi()
)有什么错?您可以使用循环?您已经有了逻辑。尝试使用@GalikYou建议的循环。您可以使用此字符串[0]-“0”
并与每个位号(10、100等)相乘总结一下。这似乎是一个家庭作业。你看了吗?你忘了符号。如果你通过增加指针而不是数组索引来遍历字符串,那么当前字符更自然的语法应该是*str
,而不是str[0]
。两者都有效且可读,但*str
可读性更强,我同意-将代码更改为纯指针表示法
int i,ans;
char num[] = "5678";
int l = strlen(num);
ans = 0;
for(i=0;i<l;i++)
ans = ans*10 + (num[i]-'0');
printf("%d\n",ans);