将字符串分割整数 [英] Splitting a string into integers
本文介绍了将字符串分割整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有关我的第一个任务,我使用与fgets()
读取标准输入
的字符串。因此我需要输入 1234567890
在终端上,它存储字符串到一个名为 STR
变量。现在我想分裂数字和执行加法。在这种情况下,款项将 55
,因为 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 0 = 55
。
我怎么能这样做?
我的code到目前为止
的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;
诠释主要(无效){焦炭海峡[100];的printf(请输入10位数字\\ n);
与fgets(STR,10,标准输入);//分离数字
//计算它们的和
INT总和= ..............//打印出总和
输出(的数字的总和是:%的,总和);返回(0);
}
解决方案
既然你确定将字符串包含数字,从减去每一个字符'0'
来得到他们的数值。
INT总和= 0;
与fgets(海峡,sizeof的STR,标准输入);
字符* S =&放大器; STR;
而(* S!='\\ 0'){
总和+ = *(S +) - '0';
}的printf(的数字的总和是:%D,总和);
For my first task I am using fgets()
to read a string from stdin
. So I input 1234567890
on the terminal and it stores the string into a variable called str
. Now I want to split the digits up and perform addition. In this case the sum would be 55
since 1+2+3+4+5+6+7+8+9+0 = 55
.
How can I do that?
My code so far
#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);
}
解决方案
Since you are sure the string will contain digits, subtract each character from '0'
to get their numeric value.
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);
这篇关于将字符串分割整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文