1

I was studying for a quiz and while writing the code I faced a problem.

My code skips the gets() function. If I use scanf it wont skip but since I'm scanning a full name using scanf would be troublesome but gets() is skipped for some reason.

struct Conta{

    char nomeDoCliente[50];
    int numeroDeConta;
    float saldoDeConta;

};
struct Conta conta1;

int main()
{
            switch (menu()){
            case 1 :
                defDadosDeConta();
                break;
            case 2 :
                break;
            case 3 :
                break;

            }
}

int menu(){
    int escolha;
    puts("1 - Definir dados da conta.");
    puts("2 - Depositar Dinheiro.");
    puts("3 - Levantar Dinheiro.");
    puts("4 - Sair.");
    printf("Escolha a sua operação: ");
    scanf("%d", &escolha);
    return escolha;
}
defDadosDeConta(){
    printf("Insira o seu nome: ");
    gets(conta1.nomeDoCliente);
    puts("Dados de conta guardados com sucesso!");


}
Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73
Javabeginner
  • 85
  • 2
  • 8

1 Answers1

3

First, never use gets as it is insecure. The safer alternative is fgets.

Even if you use that, mixing scanf and fgets causes problems because the former may leave a newline in the input buffer, causing the latter to stop once it reads that newline.

Change to scanf to read the string:

scanf("%49[^\n]", conta1.nomeDoCliente);

The format specifier %49[^\n] states to read up to 49 non-newline characters.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • %49[^\n] did fix my problem. I think the issue was that after i canned for the conta1.nomeDoCliente some background issue were happening. – Javabeginner May 25 '18 at 16:05