0

I'm doing a contact list, but I'm having problems with using gets() in visual studio. The code below is inside a switch statement.

    if (nome[i][0] == 0 && numero[i] == 0){
    printf("Nome:\n");
    fflush(stdin);
    gets(nome[i]);
    printf("Numero:\n");
    scanf("%d", &numero[i]);
    }

The problem that I'm having is that the gets() is skipped, but if I put a scanf("%c", &c) before the gets() like this it works.

    if (nome[i][0] == 0 && numero[i] == 0){
    printf("Nome:\n");
    fflush(stdin);
    scanf("%c", &c);
    gets(nome[i]);
    printf("Numero:\n");
    scanf("%d", &numero[i]);
    }

Someone told me that the problem causing this is a known problem with the visual studio console and there is a fix, but I can't find anything related to it on the internet. If someone told me what to do to fix it it would be really helpfull. If I put the first code in another IDE it works.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Gonzy
  • 1
  • 3
  • 2
    Never ***ever*** use `gets`. It's a [dangerous](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) function that have even been removed from the C standard. Use e.g. [`fgets`](https://en.cppreference.com/w/c/io/fgets) instead (but be aware of its different semantics regarding the newline). – Some programmer dude Sep 25 '19 at 12:02
  • Also calling `fflush` with an input-only stream (like `stdin`) is explicitly marked as undefined behavior in the C specification. Some systems add it as a non-portable extension, but try to avoid it. – Some programmer dude Sep 25 '19 at 12:03
  • As for your problem, think about what happens with the `Enter` key you press after the character input. – Some programmer dude Sep 25 '19 at 12:04

1 Answers1

0

The function gets is not a standard C function. It is unsafe. The problem with your code is that after entering an integer the new line character is still in the input biffer and a next call of gets reads an empty string until the new line character is encountered.

Use instead the standard C function fgets.

If for example the expression nome[i] has a character array type then you can write

fgets( nome[i], sizeof( nome[i] ), stdin );

and then you need to remove the new line character from the string that is read into the array. For example

nome[i][ strcspn( nome[i], "\n" ) ] = '\0';

Pay attention to that this call

fflush(stdin);

has undefined behavior. Remove it.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335