如何对结构体数组使用gets函数
时间: 2023-12-13 16:03:28 浏览: 175
在 C 语言中,`gets()` 函数用于从标准输入(键盘)读取字符串,它的用法如下:
```c
char * gets(char * str);
```
这个函数会读取用户输入的字符串,并将其存储到 `str` 所指向的字符数组中,直到遇到换行符(`\n`)为止。需要注意的是,`gets()` 函数是不安全的,因为它没有对输入的字符串长度进行检查,容易导致缓冲区溢出的问题。
对于结构体数组,如果要使用 `gets()` 函数进行信息录入,可以按照以下方式进行:
```c
#include <stdio.h>
struct MyStruct {
int num;
char name[20];
};
int main() {
struct MyStruct luru[10];
// 录入信息
for(int i = 0; i < 10; i++) {
printf("请输入第 %d 个结构体的数字和名字:\n", i+1);
scanf("%d", &luru[i].num);
getchar(); // 读取多余的换行符
gets(luru[i].name);
}
// 打印录入的信息
for(int i = 0; i < 10; i++) {
printf("第 %d 个结构体的数字为:%d,名字为:%s\n", i+1, luru[i].num, luru[i].name);
}
return 0;
}
```
在这个例子中,我们在录入数字后使用 `getchar()` 函数读取多余的换行符,防止其对 `gets()` 函数的调用产生影响。然后我们使用 `gets()` 函数读取字符串类型的数据,存储到结构体数组的相应成员变量中。最后通过循环打印出录入的信息。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)