笔者并没有按照题目要求来写,但是测试通过。如有其它解法,欢迎交流。
从键盘输入一串字符(假设字符数少于8个),以回车表示输入结束,编程将其中的数字部分转换为整型数并以整型的形式输出。
函数原型为 int Myatoi(char str[]);
其中,形参数组str[]对应用户输入的字符串,函数返回值为转换后的整型数。
解题思路的关键是:1)判断字符串中的字符是否是数字字符;2)如何将数字字符转换为其对应的数字值;3)如何将每一个转换后的数字值加起来形成一个整型数。
程序运行结果示例1:
Input a string:7hg09y↙
709
程序运行结果示例2:
Input a string:9w2k7m0↙
9270
程序运行结果示例3:
Input a string:happy↙
0
#include <stdio.h>
#include <string.h>
void Myatoi(char str[]);
int main()
{
char str[8];
printf("Input a string:");
scanf("%7s",&str);
Myatoi(str);
printf("\n");
return 0;
}
void Myatoi(char str[])
{
char *p=str;
int i=0;
for(;*p!='\0';*p++)
{
if('0'>=*p || *p<='9')//如果有0~9的字符
{
printf("%d",*p-48);//转换成整型输出
i++;
}
}
if(i==0)//如果没有,则输出0
printf("%d",i);
}