Gets function on Linux

Asked

Viewed 1,886 times

3

I’m trying to use the function gets (language C), but it doesn’t work. Am I using it wrong? The code is 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);

    }
}
  • 2

    Always inform in your question what the problem is occurring.

2 answers

6

What happens is that the gets picks up the " n" that the scanf leaves, so much so that if you reverse the order of the scanf with the gets will work.

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

You can also try using the:

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

Another way is you take the " n" that the scanf leaves with the getchar() and then use the gets, so here 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);

    }
}
  • Yes, reversing the order really works. But I will follow the advice and use the fgets. Brigade!

  • Take a look at another solution I gave

  • can I ask one more question?

  • If the answer solves your problem don’t forget to mark it as solved so that other people see the solution :)

  • I need to add the notes inside the array of structures as I do this?

  • I recommend opening another question so we don’t run away from the scope of this question here.

Show 1 more comment

0

Just using gets() is already a mistake :-)

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 inform her the maximum space she can fill (if the compiler still accepts gets, it’s his problem - don’t use it anyway)

My suggestion:

Read all lines 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 the scanf, but reads from a ready-made string instead of reading straight from the keyboard.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.