用c语言从键盘输入一串字符(假设字符数少于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"
时间: 2023-07-16 07:12:27 浏览: 111
以下是实现 Myatoi 函数的 C 语言代码:
```c
#include <stdio.h>
int Myatoi(char str[]) {
int i = 0;
int num = 0;
while (str[i] != '\0') {
if (str[i] >= '0' && str[i] <= '9') {
num = num * 10 + (str[i] - '0');
}
i++;
}
return num;
}
int main() {
char str[8];
printf("Input a string:");
scanf("%7s", str);
int num = Myatoi(str);
printf("%d\n", num);
return 0;
}
```
该程序首先定义了 Myatoi 函数,用于将输入的字符串中的数字部分转换为整型数。函数中使用了 while 循环遍历输入字符串中的所有字符,如果该字符是数字字符,则将其转换为对应的数字值,并将其加到已经处理的数字值的后面。最后返回整型数 num 即可。
在主函数中,程序首先提示用户输入字符串,然后使用 scanf 函数读取用户输入的字符串,并将其存储在字符数组 str 中。由于字符数少于 8 个,所以我们使用 "%7s" 格式化字符串来限制最多只能读取 7 个字符。接着调用 Myatoi 函数将字符串中的数字部分转换为整型数,最后使用 printf 函数输出转换后的整型数。
程序的输出结果与要求相符,可以通过本题的测试。
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)