#include<stdio.h> #include<stdlib.h> #include<string.h> #define SIZE 256 //字符串最大长度+1 #define is_number(ch) ((‘0‘<=(ch)) && ((ch)<=‘9‘)) //判断字符是否为数字 int main(){ char * str=(char *)malloc(SIZE); //声明字符串并给它分配内存 int a[SIZE]={0},count=0; //数组a存储整数,count统计整数数量 fgets(str,SIZE,stdin); for(int i=0;i<strlen(str);i++){ if(is_number(*(str+i))){ a[count]=10*a[count]+*(str+i)-48; //在ASCII码中,一个数字减去48是它本身的码值 if(!is_number(*(str+i+1))) count++; //下一个字符不是数字,则单个整数完成统计 } } printf("一共有%d个整数\n",count); for(int i=0;i<count;i++) printf("第%d个是%d\n",i+1,a[i]); system("pause"); return 0; }
输入:114iiyo514koiyo1919tdkr810ton
输出:
一共有4个整数
第1个是114
第2个是514
第3个是1919
第4个是810
题目来源:《C程序设计 第五版》谭浩强 第八章16题
原文:https://www.cnblogs.com/adesoe/p/12815657.html