获取结构的用户输入的问题

问题描述 投票:0回答:1

我试图从用户获取结构中字符串的输入。但是,当尝试使用scanf获取输入时,显然有两个字符串存储在结构的第一个字符数组中。字符串的输入由空格分隔。这就是为什么我试图用scanf来做它因为我不知道它是否有可能使用fgets用空格分隔输入。

我也尝试将struct成员更改为指向字符数组的指针,并使用malloc为字符串分配内存,但在输入后仍然保持seg错误。

#define MAXID 6
#define FIRST_NAME_LENGTH  20
#define LAST_NAME_LENGTH   20

struct student
{
    char ID[MAXID];
    char f_name[FIRST_NAME_LENGTH];
    char s_name[LAST_NAME_LENGTH];
    int points[MAXROUNDS];
};

struct student studentinfo;

.......

void student_info(struct student *studentinfo)
{
    printf("Give the students ID, surname and firstname.\n");
    scanf("%s%s%s", studentinfo->ID, studentinfo->s_name, studentinfo->f_name);
}

printf("Info of the last student added: %s %s %s\n", studentinfo.ID, studentinfo.s_name, studentinfo.f_name);

因此输入“666666 boi bobby”输出为“666666bobby boi bobby”。做什么?

c struct scanf
1个回答
2
投票

ID大小如果为6,但你为它输入6个字符,没有地方可以保存到f_name的第一个字符中的空结尾字符被bobby的'b'删除,所以当你打印ID时没有其中的空字符所以打印继续写f_name的内容生成666666bobby然后s_name是打印生产boi然后f_name打印(再次)生产鲍比

输入66666而不是666666或增加ID的大小,该行为消失

这就是为什么必须使用保护来避免在使用scanf读取字符串时溢出

© www.soinside.com 2019 - 2024. All rights reserved.