我想加上数字形式的字符串数据类型

时间:2019-05-29 06:06:38

标签: c atoi

我将以下输入作为字符串:

Num: 12345

我想从输入中打印出数字的总和(1 + 2 + 3 + 4 + 5 = 15):

total:15

我尝试过,但是atoi()循环中的for存在问题,但出现错误:

  

[错误]从'char'到'const char *'的无效转换

如何解决该问题或如何以更简单的方式解决它?

 #include <stdio.h>
 #include <ctype.h>
 #include <stdlib.h>
 #include <string.h>

 char numstr[100];
 int total = 0;

 main(){
     printf("Num:");
     scanf("%s", numstr);

     for(int i = 0; i < strlen(numstr); i++){
         total += atoi(numstr[i]);
     }
     printf("%d", total);
 }

5 个答案:

答案 0 :(得分:2)

您可以将数字字符(以ASCII形式)减去0x30(即ASCII字符零“ 0”),以将ASCII数字字符转换为其等效的十进制数。

 #include <stdio.h>
 #include <ctype.h>
 #include <stdlib.h>
 #include <string.h>
 char numstr[100];
 int total=0;
 main(){
 printf("Num:");
 scanf("%s",numstr);

 for(int i = 0;i<strlen(numstr);i++){
     total += numstr[i] - 0x30;
 }
 printf("%d",total);
 }

字符串“ 12345”将是

1 -> 0x31 - 0x30 = 1
2 -> 0x32 - 0x30 = 2
3 -> 0x33 - 0x30 = 3
4 -> 0x34 - 0x30 = 4
5 -> 0x35 - 0x30 = 5

答案 1 :(得分:1)

您可以通过减去数字字符来获得数字字符的整数值。

total += numstr[i] - '0';

这是因为0字符的值等于十进制的48(或十六进制的0x30),1字符等于十进制的49十进制,250等。

从自身中减去0字符,得到0(十进制)。从字符0中减去1字符得到1(十进制),依此类推。

答案 2 :(得分:0)

atoi()并没有您认为的那样。

实现所需目标的一种可能方法是使用atoi(),或者更好的使用strtol()将用户输入转换为整数类型,然后使用取模运算符提取每个数字并将其相加

 #include <stdio.h>
 #include <ctype.h>
 #include <stdlib.h>
 #include <string.h>


 int main(void){                     //correct signature

     int total=0;                    // no need to be global
     char numstr[100] = {0};         // same
     int ret = -1;

     printf("Num:");
     ret = scanf("%99s",numstr);       
     if (ret != 1){                    // basic sanity check for scanf
         printf("Error in scanning\n");
         exit (-1);
     }

     long int converted = strtol(numstr, NULL, 10);   // convert to integer
     printf("%ld\n\n", converted);

     for (int i = 0; converted; i++){

         total += converted %10;                // add the digit
         converted /= 10;                       // reduce the last added digit
     }

     printf("%d",total);
     return 0;                               // return 0 is implicit for `main()`, anyways
 }

答案 3 :(得分:0)

简单!将输入作为字符串,然后将字符减去“ 0”。这将为您提供该特定位置的电话号码。参见下面的代码:

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
char numstr[100];
int total=0;
main(){
printf("Num:");
scanf("%s",numstr);

for(int i = 0;i<strlen(numstr);i++){
 total += (numstr[i]-'0');
}
printf("%d",total);
}

省去了使用atoi()或其他函数的麻烦。

答案 4 :(得分:0)

更简单的方法来解决您的问题

total += atoi(numstr[i]);

使用

total += numstr[i] - '0';

您可能想先检查isdigit(numstr [i])是否为真,以进行错误检查。