Scanf()读取自己的输入和以下scanf()的输入

时间:2017-01-16 14:17:06

标签: c string scanf

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

CODE:

#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

2 个答案:

答案 0 :(得分:4)

您正在覆盖空格以终止空字符

你有:

#define MAX_LEN_CODE 6

和您的struct t_course

char course_code[MAX_LEN_CODE];

因此course_code可以存储5个字符+ 1来终止空字符,即'\0'来标记字符串的结尾,但是你通过提供6个字符来覆盖空格以终止空字符:< / p>

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);

答案 1 :(得分:2)

course_code是一个包含六个char的数组,只能存储一个由五个字符组成的 NUL终止的字符串(因为NUL占用了一个char)。由于代码实际上是六个字符长,NUL将存储在course_code+6,这恰好是name中的第一个字节。因此,当您将字符串读入name时,NUL会被覆盖,并最终无意中连接两个字符串。