我试图将字符串转换为整数,然后再执行一些算术运算。
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句