辐射神秘客:tc输入一段文字,求其数字的和?

来源:百度文库 编辑:高考问答 时间:2024/05/04 07:16:15
输入一段文字,求其数字的和?例如,sjh1as2a3d34s和为13。

// zd_69.cpp : Defines the entry point for the console application.
//

#include <stdio.h>
int main(int argc, char* argv[])
{
char buffer[81];
int i,ch,num=0;

printf( "输入字符串: " );

/* Read in single line from "stdin": */
for( i = 0; (i < 80) && ((ch = getchar()) != EOF)
&& (ch != '\n'); i++ )
{
if(ch>=48 && ch<=57)
num++;
buffer[i] = (char)ch;
}

/* Terminate string with null character: */
buffer[i] = '\0';
printf("字符串:\n");
printf( "%s\n", buffer );
printf("数字的个数为:%d\n",num);

return 0;
}

运行结果:
输入字符串: 85j5687gfk
字符串:
85j5687gfk
数字的个数为:6
Press any key to continue

用循环把字符串的每个字符的ASCII值取出来进行比较就能确定是否数字字符,再把数字字符转换为数值,累加即可。