c语言输入n个字符串,分别输出每个字符串中的最大和最小字符。
时间: 2024-05-07 16:20:00 浏览: 17
下面是一个示例代码,其中使用了`fgets`函数读取字符串,然后遍历字符串找到最大和最小字符。需要注意的是,字符串中可能包含空格和换行符,因此需要使用`isspace`函数判断字符是否为空格或换行符。
```c
#include <stdio.h>
#include <ctype.h>
#define MAX_LEN 100
int main() {
int n;
char str[MAX_LEN];
printf("Enter the number of strings: ");
scanf("%d", &n);
getchar(); // consume the newline character
for (int i = 0; i < n; i++) {
printf("Enter string %d: ", i + 1);
fgets(str, MAX_LEN, stdin);
int max_char = str[0], min_char = str[0];
for (int j = 1; str[j] != '\0'; j++) {
if (!isspace(str[j])) {
if (str[j] > max_char) {
max_char = str[j];
}
if (str[j] < min_char) {
min_char = str[j];
}
}
}
printf("Max char: %c, min char: %c\n", max_char, min_char);
}
return 0;
}
```
这个代码中,使用`getchar()`函数来消耗输入数字后的回车符,防止它被下一个`fgets`函数读取到。对于每个字符串,使用一个循环来遍历字符串中的每个字符,并且使用`isspace`函数来判断字符是否为空格或换行符。如果不是空格或换行符,就和当前的最大和最小字符比较,更新它们的值。最后输出最大和最小字符即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)