C语言实现输入一个字符串,把该字符串中的正整数数字提取出来,保存到一个int num[N]数组里并打印
时间: 2023-05-25 20:02:33 浏览: 56
```c
#include <stdio.h>
#include <ctype.h>
#define N 100
int main() {
char str[N];
int num[N], count = 0;
printf("请输入一个字符串:\n");
fgets(str, N, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (isdigit(str[i])) {
int n = str[i] - '0';
i++;
while (isdigit(str[i])) {
n = n * 10 + (str[i] - '0');
i++;
}
num[count++] = n;
}
}
printf("提取出的数字为:");
for (int i = 0; i < count; i++) {
printf("%d ", num[i]);
}
printf("\n");
return 0;
}
```
相关问题
c语言输入一个字符串 把字符串的正整数取出 保存在数组里打印
以下是一个示例程序,输入一个字符串,将其中的正整数取出并保存在数组中,最后打印出来:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_STR_LEN 100
int main() {
char str[MAX_STR_LEN];
int nums[MAX_STR_LEN];
int num_count = 0, i, j;
printf("Please enter a string:\n");
fgets(str, MAX_STR_LEN, stdin);
// Iterate through the string
for (i = 0; i < strlen(str); i++) {
// If current character is a digit
if (isdigit(str[i])) {
// Keep going until a non-digit is found
int num = 0;
while (isdigit(str[i])) {
num = num * 10 + (str[i] - '0');
i++;
}
// Save the number in the array
nums[num_count] = num;
num_count++;
}
}
// Print out the numbers found
printf("The positive integers found in the string are:\n");
for (j = 0; j < num_count; j++) {
printf("%d ", nums[j]);
}
printf("\n");
return 0;
}
```
示例输出:
```
Please enter a string:
abc12 def34 jkl56 78mno
The positive integers found in the string are:
12 34 56 78
```
用C语言输入一数字字符串,将其转化为正整数。
可以使用C语言中的库函数 `atoi` 来将数字字符串转化为正整数。下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[100];
printf("请输入一个数字字符串:");
scanf("%s", str);
int num = atoi(str);
printf("转换后的正整数为:%d", num);
return 0;
}
```
在上面的代码中,我们先定义了一个字符数组 `str` 来存储用户输入的数字字符串,然后使用 `scanf` 函数从标准输入读取字符串。接着,我们使用 `atoi` 函数将字符串转换为整数,并将结果保存在 `num` 变量中。最后,我们使用 `printf` 函数将转换后的正整数输出到屏幕上。
需要注意的是,`atoi` 函数只能将合法的数字字符串转换为整数,如果输入的字符串不是合法的数字字符串,那么转换结果可能是不可预测的。因此,在实际应用中,需要对输入的字符串进行合法性检查。