将字符串拆分为整数

时间:2015-03-24 14:18:18

标签: c string

对于我的第一项任务,我使用fgets()stdin读取字符串。所以我在终端上输入1234567890并将字符串存储到名为str的变量中。现在我想分开数字并执行添加。在这种情况下,总和将是55,因为1+2+3+4+5+6+7+8+9+0 = 55

我该怎么做?

到目前为止我的代码

#include <stdio.h>
#include <string.h>
int main(void){

char str[100];

printf("Please enter the 10 digit number \n");
fgets(str, 10, stdin);

//Separate the digits


//calculate their sum
int sum =..............

//print out the sum
printf("the sum of the digits is: %s", sum);

return(0);
}

3 个答案:

答案 0 :(得分:5)

方法1:

如果您确定自己计算单位数整数,则可以使用

  • 数组索引以从输入字符串中读取逐位值。
  • 根据所需的编码将char值转换为对应的int(主要是ASCII)。
  • 定义一个int变量,比如res来保存总和。执行添加并将结果存储到sum
  • 循环,直到达到终止null。
  • 使用sum格式说明符打印%d

方法2:

或者,您可以执行类似的操作(再次假设单个数字整数

  • 使用strtol()将整个字符串转换为整数。在这种情况下,您必须检查错误。
  • 定义一个int变量,比如res来保存总和。
  • 执行模数10% 0 ) on the converted interger value to take out the last digit. add and store that in res`
  • 将转换后的整数值除以10p /= 10)。
  • 继续执行第2步,直到结果为0
  • 当转换后的整数值变为0时,请打印res

P.S - 仅供参考,基于某些分隔符分割字符串的常用方法是使用strtok()

答案 1 :(得分:0)

首先,请确保您只使用scanf读取数字,如下所示:

char str[11]; // 10 digits plus \0 terminator
printf("Please enter the 10 digit number \n");
scanf("%10[0-9]", str);

现在你可以通过索引到str逐个查看数字,然后减去数字零的代码,如下所示:

int nextDigit = str[i] - '0';

这应该足以让您通过在其周围添加for循环来完成解决方案。确保使用sum打印%d,而不是像代码示例中那样打印%s

答案 2 :(得分:0)

由于您确定该字符串将包含数字,请从'0'中减去每个字符以获取其数字值。

int sum = 0;
fgets(str, sizeof str, stdin);
char *s = &str;
while(*s != '\0') {
    sum += *(s++) - '0';
}

printf("the sum of the digits is: %d", sum);
相关问题