数字字符串转换为整型数

题目内容:

从键盘输入一串字符(假设字符数少于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

输入提示信息:"Input a string:"

输入格式: "%7s"

输出格式:"%d\n"

注意:为避免出现格式错误,请直接拷贝粘贴上面给出的输入、输出提示信息和格式控制字符串!

时间限制:500ms内存限制:32000kb

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int Myatoi(char str[])
{
int i,j;
for(i=0,j=0;str[i]!='\0';i++)
{
if(str[i]>='0'&&str[i]<='9')
{
str[j]=str[i];
j++;
}
}
str[j]='\0';
return atoi(str);
}
int main()
{
char s[7];
printf("Input a string:");
scanf("%7s",s);
printf("%d\n",Myatoi(s));
return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40629792/article/details/79014261