如何输入一个字符数组
时间: 2024-06-14 16:05:35 浏览: 6
以下是两种输入字符数组的方法:
1. 使用for循环逐个输入字符:
```c
char str[10];
int i;
for(i=0; i<10; i++){
scanf("%c", &str[i]);
}
```
2. 使用fgets函数输入二维字符数组:
```c
char str[10][81];
int i;
for(i=0; i<10; i++){
fgets(str[i], 81, stdin);
}
```
相关问题
输入一个字符数组,统计数组里A和B的数量
好的,以下是一个示例代码,可以输入一个字符数组,并统计其中 A 和 B 的数量:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int len, i, count_a = 0, count_b = 0;
printf("请输入一个字符数组:");
scanf("%s", str);
len = strlen(str);
for (i = 0; i < len; i++) {
if (str[i] == 'A') {
count_a++;
}
if (str[i] == 'B') {
count_b++;
}
}
printf("字符数组中 A 的数量为:%d\n", count_a);
printf("字符数组中 B 的数量为:%d\n", count_b);
return 0;
}
```
代码中使用了 scanf() 函数来输入一个字符数组,使用 strlen() 函数获取字符数组的长度,然后使用 for 循环遍历每个字符,统计其中 A 和 B 的数量。最后输出结果。
c语言如何实现输入一个字符数组,统计数组里A和B的数量
可以使用C语言中的循环结构和条件语句来实现输入一个字符数组,统计数组里A和B的数量。具体实现可以参考以下代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int len, a_count = 0, b_count = 0;
printf("请输入一个字符数组: ");
scanf("%s", str);
len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] == 'A') {
a_count++;
} else if (str[i] == 'B') {
b_count++;
}
}
printf("数组中A的数量为: %d\n", a_count);
printf("数组中B的数量为: %d\n", b_count);
return 0;
}
```
在上述代码中,首先定义了一个字符数组`str`,用于存储输入的字符数组;然后通过`scanf()`函数获取用户输入的字符数组;接着使用`strlen()`函数获取字符数组的长度;最后使用循环结构和条件语句遍历数组中的每一个字符,统计A和B的数量,并将结果输出。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)