我很困惑这个错误,不明白哪里出了问题。我已经进行了一些调试,但它并没有按照正确的方式执行。由于某种原因,第一个
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
fgets
获取用户输入,而不是scanf
。 - melpomeneint
而不是void
? - reusemanint main(void)
和int main(int argc, char **argv)
;其他任何内容都是针对特定系统(如果你的编译器文档不支持void main
,那么可能就不行)。另请参见 http://c-faq.com/ansi/maindecl.html。 - melpomenevoid main() {}
?这种写法曾经可以接受吗? - ad absurdumscanf()
。如果你在%s
中指定了最大宽度,scanf()
也可以提供一些溢出保护。但是scanf()
很棘手且容易出错,这就是为什么你会在这里看到很多避免使用它的建议。 - ad absurdum