Function gets on Linux

3

I'm trying to use the gets (C language) function, but it does not work. Am I using it the wrong way? The code looks like this:

#include <stdio.h>

typedef struct {
    int matricula;
    char nome[40];
    int nota_1;
    int nota_2;
    int nota_3;

}aluno;

int main (){
    aluno a[5];
    int i;
    for (i=0; i<5; i++){
        printf("Matricula\n");
        scanf("%d", &a[i].matricula);
        printf("Nome\n");
        gets(a[i].nome);
        printf("Nota das provas\n");
        scanf("%d %d %d", &a[i].nota_1, &a[i].nota_2, &a[i].nota_3);

    }
}
    
asked by anonymous 29.10.2014 / 22:33

2 answers

6

What happens is that gets gets the "\ n" that the scanf leaves, so much so that if you reverse the scanf command with gets will work.

In this case, use fgets as Broly mentioned, this will solve your problem.

You can also try using the:

scanf("%d", &a);
getc(stdin);

Another way is to get the "\ n" that scanf leaves with getchar () and then use gets, so here it also works:

int main (){
    aluno a[5];
    int i;
    for (i=0; i<5; i++){
        printf("Matricula\n");
        scanf("%d", &a[i].matricula);
        getchar();
        printf("Nome\n");
        gets(a[i].nome);
        printf("Nota das provas\n");
        scanf("%d %d %d", &a[i].nota_1, &a[i].nota_2, &a[i].nota_3);

    }
}
    
29.10.2014 / 22:47
0

Just using gets () is already an error: -)

No, I'm not being the boring guy in the class, really this function has no place in the current programming and has already been officially removed from the C language, because there is no way to tell it the maximum space it can fill (if the compiler still accept gets, problem is his - do not use anyway)

My suggestion:

Read all rows with fgets . When you need to extract a number from one of these lines, use sscanf (notice that you have a s at the beginning of the function name). This function does the same as scanf , but reads from a ready string instead of reading directly from the keyboard.

    
30.10.2014 / 13:28