gpt4 book ai didi

c - scanf()读取自己的输入和后面scanf()的输入

转载 作者:太空狗 更新时间:2023-10-29 16:05:48 25 4
gpt4 key购买 nike

这个错误让我失去了理智,我无法理解它有什么问题。我已经进行了一些调试以使其工作,但它并没有以正确的方式进行。由于某种原因,第一个 scanf() 读取两个输入,它自己的输入和后面的 scanf() 的输入。顺便说一句,我正在使用 %[^\n]s,因为这样它应该读取带有空格的字符串。我怎样才能解决所有问题?

代码:

#include <stdio.h>
#include <stdlib.h>

#define MAX_LEN_CODE 6
#define MAX_LEN_STRING 20

typedef struct{
char course_code[MAX_LEN_CODE];
char name[MAX_LEN_STRING];
char trainer[MAX_LEN_STRING];
int partecipants_max;
int partecipants_num;
}t_course;

void main(){
t_course new_course;

system("clear");
printf("Insert the code\n");
printf("> ");
scanf("%s", new_course.course_code);
printf("Insert the name of the course\n");
printf("> ");
scanf(" %[^\n]s", new_course.name);
printf("Insert the trainer\n");
printf("> ");
scanf("%s", new_course.trainer);
do{
printf("Insert the maximum number of partecipants (10-100)\n");
printf("> ");
scanf("%d", &new_course.partecipants_max);

if(new_course.partecipants_max < 10 ||
new_course.partecipants_max > 100)
printf("ERROR: The number must be between 10 and 100!\n\n");

}while(new_course.partecipants_max < 10 ||
new_course.partecipants_max > 100);

new_course.partecipants_num = 0;

printf("\nCODE: %s\nNAME: %s\nTRAINER: %s\nPARTECIPANTS: %d\n",
new_course.course_code, new_course.name,
new_course.trainer, new_course.partecipants_max);
}

输出:

Insert the code
> aa3040
Insert the name of the course
> fitness and sport
Insert the trainer
> mario
Insert the maximum number of partecipants (10-100)
> 55

CODE: aa3040fitness and sport // I CAN'T FIGURE OUT THIS STEP
NAME: fitness and sport
TRAINER: mario
PARTECIPANTS: 55

最佳答案

您正在覆盖终止空字符的空间:

你有:

#define MAX_LEN_CODE 6

在你的struct t_course中:

char course_code[MAX_LEN_CODE];

所以 course_code 可以存储 5 个字符 + 1 个用于终止空字符,即 '\0' 来标记字符串的结尾,但是你正在覆盖通过提供 6 个字符来终止空字符:

aa3040

尝试提供 +1 长度:

//changing MAX_LEN_CODE value:
#define MAX_LEN_CODE 7

//or instead of changing MAX_LEN_CODE
//change the size of course_code in your struct:
char course_code[MAX_LEN_CODE + 1];

或者通过提供宽度说明符使scanf()只接受5个字符以避免覆盖末尾的终止空字符:

scanf("%5s", new_course.course_code);

//NOTE: You still need to consume the characters left in stdin
int consume;
while((consume = getchar()) != '\n' && consume != EOF);

关于c - scanf()读取自己的输入和后面scanf()的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41678430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com