Scanf won't continue after I seized an input text

时间:2017-07-12 07:59:34

标签: c arrays

so, I am basically building an array of students with their evaluation.

I made a basic struct :

struct Eleve{
    char Nom[100];
    int Note;
};

struct Eleve *array;

Then asking for how many children I want to input into my array, then loop and asking information for each child. But, when I enter an input into scanf("%s\n", array[i].Nom); the code stop.

    int nbEleves;
    float total = 0;
    printf("Nombre?!\n");
    scanf("%d", &nbEleves);

    array = malloc(nbEleves * sizeof(struct Eleve));
    int i = 0;
    while (i < nbEleves) {
        printf("Nom? ");
        scanf("%s\n", array[i].Nom);
        printf("La note? ");
        scanf("%d\n", &array[i].Note);
        total = total + array[i].Note;
        i++;
    }

It doesn't even go on the next printf. I don't understand why, because I don't get any build error or execution errors on this line. Eventually I would have looked at the format if by any chance I'd get an error there, but nothing. No errors, just not getting to the next step of the program.

I think my scanf looks right, and I've got no warnings on it. So, what can prevent the code to go further?

The data I entered in Nom is test.

2 个答案:

答案 0 :(得分:2)

你不应该使用scanf!这是一个古老的讨论,使用scanf需要小心并且是危险的。 Disadvantages of scanf

而是使用fgets()

检查此答案How to read from stdin with fgets()?或此 Not able to input a string with spaces in a loop in C

但是如果你仍然坚持使用scanf(),这可能很有用:

 while(i<nbEleves){
        printf("Nom? ");
        scanf(" %[^\n]",array[i].Nom);// remove the \n and notice the space before %[^\n]
        printf("La note? ");
        scanf("%d", &array[i].Note);
        total = total + array[i].Note;
        i++;
}

另外,我建议您必须释放使用free()分配的内存,以防止内存泄漏。

free(array);

答案 1 :(得分:1)

\nscanf("%s\n", array[i].Nom);移除scanf("%d\n", &array[i].Note);或在插入值后按CTRL + D