我正在尝试获取输入数据并使用结构打印它。当我运行此代码时,它没有输入lastname的输入。它直接要求输入firstname的输入。有人可以帮我弄这个吗。谢谢。
address.c
typedef struct
{
char lname[25];
char fname[20];
char address[20];
char phonenumber[20];
}addressbook;
addressbook a;
int main()
{
printf("enter details:\n");
printf("enter lastname:\n");
gets(a.lastname);
printf("enter firstname:\n");
gets(a.firstname);
printf("enter address:\n");
gets(a.address);
printf("enter phone number:\n");
gets(a.phonenumber);
printf("lastname:%s\n",a.lastname);
printf("firstname: %s\n", a.firstname);
printf("address:%s\n", a.address);
printf("phone number:%s\n", a.phonenumber);
}
当我运行它时,它不等待输入姓氏。它直接进入名字。
答案 0 :(得分:0)
该代码甚至不会编译,因为它产生(在我的环境中):
pax@pax-desktop:~$ gcc -Wall -Wextra -o qq qq.c
qq.c: In function ‘main’:
qq.c:12:2: warning: implicit declaration of function ‘printf’
qq.c:12:2: warning: incompatible implicit declaration of built-in function ‘printf’
qq.c:14:4: warning: implicit declaration of function ‘gets’
qq.c:14:10: error: ‘addressbook’ has no member named ‘lastname’
qq.c:16:10: error: ‘addressbook’ has no member named ‘firstname’
qq.c:21:28: error: ‘addressbook’ has no member named ‘lastname’
qq.c:22:31: error: ‘addressbook’ has no member named ‘firstname’
qq.c:25:1: warning: control reaches end of non-void function
您应该始终(至少最初)使用高警告级别进行编译,并记下编译器告诉您的内容:
stdio.h
和printf
,则应添加gets
。此外,您可能需要考虑以下事项:
int main()
不是main
函数的两种规范形式之一。虽然标准的允许用于实现定义的额外的,但对于这个特定情况,“正确的”将是int main (void)
。gets
是一个危险的函数,因为无法防止缓冲区溢出,使您的代码不安全。例如,如果我输入了一千个字符作为我的名字,它可能会通过覆盖堆栈上的大量会计信息(例如返回地址)来搞砸你的程序。您可以找到更安全的输入函数here。进行大多数这些更改,您最终会得到类似的结果:
#include <stdio.h>
typedef struct {
char lastname[25];
char firstname[20];
char address[20];
char phonenumber[20];
}addressbook;
addressbook a;
int main (void) {
printf("enter details:\n");
printf("enter lastname:\n");
gets(a.lastname);
printf("enter firstname:\n");
gets(a.firstname);
printf("enter address:\n");
gets(a.address);
printf("enter phone number:\n");
gets(a.phonenumber);
printf("lastname:%s\n",a.lastname);
printf("firstname: %s\n", a.firstname);
printf("address:%s\n", a.address);
printf("phone number:%s\n", a.phonenumber);
return 0;
}
编译并运行正常,尽管它仍然存在严重的缓冲区溢出漏洞。如果你想解决这个问题,你可以参考我给出的链接。