c语言输入一个字符串 把字符串的正整数取出 保存在数组里打印
时间: 2023-05-24 18:05:57 浏览: 167
字符串的存储-c语言课件\\第7章 数组
以下是一个示例程序,输入一个字符串,将其中的正整数取出并保存在数组中,最后打印出来:
```
#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
```
阅读全文