Program does not read scanf

4

I'm doing a school job, doing a blackjack (21) in C. In a certain part of the program, I created a while (while the option is yes) to show the cards, the score and ask if the user wants to bet again (yes or no) at the end of the while. Except that the compiler terminates the program and does not read the scanf at the end of the while. If anyone can tell me how to solve it, I would be grateful, I have to deliver this today.

#include <stdio.h>
#include <stdlib.h>
#define max 21

int main() {
    char naipe, nome[50], op;
    char tipo[13] = {'A','2','3','4','5','6','7','8','9','10','J','Q','K'};
    int valor, valorb, soma=0, somab=0;
    int i,din=1000;
    int aposta, taposta=0;

    printf("Digite o seu nome:\n");
    scanf("%s",&nome);
    op='S';

    do {
    system("cls");
    printf("Você tem %d unidades\n",din);
    printf("Escolha sua aposta inicial, %s:\n",nome);
    printf("Digite 1 para 10 unidades\n");
    printf("Digite 2 para 20 unidades\n");
    printf("Digite 3 para 50 unidades\n");
    scanf("%d",&aposta);
    } while (aposta<1 || aposta>3);
    switch (aposta) {
    case 1:
        taposta+=10;
        break;
    case 2:
        taposta+=20;
        break;
    case 3:
        taposta+=50;
        break;
    }


    while ((op=='s') || (op=='S')) {

        srand(time(NULL));
        i=rand()%12+1;
        if ((i==11) || (i==12) || (i==13))
            valor=10;
        else if (i==1)
            valor=1;
        else
            valor=i;
        naipe=rand()%3+3;
        soma=(soma+valor);

        printf("_________\n");
        printf("|%c      |\n",naipe);
        printf("|       |\n");
        printf("|   %c   |\n",tipo[i]);
        printf("|       |\n");
        printf("|      %c|\n",naipe);
        printf("\---------\n");

        i=rand()%12+1;
        if ((i==11) || (i==12) || (i==13))
            valorb=10;
        else if (i==1)
            valorb=1;
        else
            valorb=(i+1);
        naipe=rand()%3+3;
        somab=(somab+valorb);

        printf("_________\n");
        printf("|%c      |\n",naipe);
        printf("|       |\n");
        printf("|   %c   |\n",tipo[i]);
        printf("|       |\n");
        printf("|      %c|\n",naipe);
        printf("\---------\n");
        printf("\n");
        printf("Você marcou %d pontos e tem um total de %d pontos.\n",valor,soma);
        printf("O computador marcou %d pontos e tem um total de %d pontos.\n",valorb,somab);
        printf("\n");
        printf("Deseja fazer a jogada? [S/N]\n");
        scanf("%c",&op);
    }
}
    
asked by anonymous 12.12.2014 / 16:28

3 answers

10

I found several errors in this code:

  • missing #include <time.h> ;
  • has escaped \ in the middle of printf ;
  • can not use '10' there in the array since '10' is 2 characters;

Be careful about how to read stdin characters as you can see in this question .

Then I added the line while ( getchar() != '\n' ); to read all the characters that are in stdin .

Here it works without warnings :

#include <stdio.h>
#include <stdlib.h>
#include <time.h> 
#define max 21

int main() {
    char naipe, nome[50], op;
    char tipo[13] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K'};
    int valor, valorb, soma=0, somab=0;
    int i,din=1000;
    int aposta, taposta=0;

    printf("Digite o seu nome:\n");
    scanf("%s",nome);
    op='S';

    do {
    system("cls");
    printf("Você tem %d unidades\n",din);
    printf("Escolha sua aposta inicial, %s:\n",nome);
    printf("Digite 1 para 10 unidades\n");
    printf("Digite 2 para 20 unidades\n");
    printf("Digite 3 para 50 unidades\n");
    scanf("%d",&aposta);
    } while (aposta<1 || aposta>3);
    switch (aposta) {
    case 1:
        taposta+=10;
        break;
    case 2:
        taposta+=20;
        break;
    case 3:
        taposta+=50;
        break;
    }


    while ((op=='s') || (op=='S')) {

        srand(time(NULL));
        i=rand()%12+1;
        if ((i==10) || (i==11) || (i==12) || (i==13))
            valor=10;
        else if (i==1)
            valor=1;
        else
            valor=i;
        naipe=rand()%3+3;
        soma=(soma+valor);

        printf("_________\n");
        printf("|%c      |\n",naipe);
        printf("|       |\n");
        printf("|   %c   |\n",tipo[i]);
        printf("|       |\n");
        printf("|      %c|\n",naipe);
        printf("---------\n");

        i=rand()%12+1;
        if ((i==10) || (i==11) || (i==12) || (i==13))
            valorb=10;
        else if (i==1)
            valorb=1;
        else
            valorb=(i+1);
        naipe=rand()%3+3;
        somab=(somab+valorb);

        printf("_________\n");
        printf("|%c      |\n",naipe);
        printf("|       |\n");
        printf("|   %c   |\n",tipo[i]);
        printf("|       |\n");
        printf("|      %c|\n",naipe);
        printf("---------\n");
        printf("\n");
        printf("Você marcou %d pontos e tem um total de %d pontos.\n",valor,soma);
        printf("O computador marcou %d pontos e tem um total de %d pontos.\n",valorb,somab);
        printf("\n");
        printf("Deseja fazer a jogada? [S/N]\n");

        while ( getchar() != '\n' );

        scanf("%c",&op);

        printf("Selecionou S/N: %c\n", op);
    }
}

You can see here the example

    
12.12.2014 / 17:19
6

Give a space between the quotation mark and the% symbol in:

scanf("%s",&nome);
scanf("%d",&aposta);    
scanf("%c",&op);

It looks like this:

scanf(" %s",&nome);
scanf(" %d",&aposta);    
scanf(" %c",&op);

This is sufficient for scanf() to understand that it is a new entry.

You can also search for the fflush(stdin) function to clean the Keyboard Buffer to prevent this type of problem from occurring.

    
12.12.2014 / 16:53
3

Actually the problem is in the first and second scanf, when you press ENTER there in the first scanf the string is read and sent to variable but the '\ n' (ENTER) is in the Buffer (The string too, but ignore this parenthesis). Other things wrong: time.h library is not included; to reproduce this bar \ in printf you have to type \\ instead of simply \ and the question of '10' (2 characters) in a space in the char array.

In the second scanf you do not have this problem because you are reading an integer, only in the second scanf another '\ n' gets in the buffer after you press ENTER to enter the integer.

In the third that is the last one when you put scanf("%c",&op); it reads the '\ n' that is already in the Buffer, so it does not stop.

Solution:

Do so, whenever you use scanf use scanf("%SeuTipo%*c", &Variável) always put% * c so it will read what the user informs and will discard the '\ n' which is a character so% * c resolves. / p>

Problem

Assuming the user reports instead of 'S' report 'SS' there he would read 'S' and discard the other 'S' and the '\ n' would continue in Buffer.

Other Solutions

Normally to avoid wrong data, you create a string and read everything the user says and places it on it and then type them with a regex that is simple to work with, fgets (which is most recommended) or a validation like this:

For example, you need the user to report only integers

#include <stdio.h>
#include <stdlib.h>
#include <string.h> //Para usar strlen()

int main(){
    char string[100];
    int a = 0, i = 0;


    printf("Informe um inteiro: ");
    scanf("%[^\n]s", &string); //Esse [^\n] Faz Ele Ler Tudo Menos O '\n'
    getchar(); // Usamos O scanf, Agora Em Baixo Dele Um getchar() Para Pegar O '\n' E Descartá-lo

    for (i = 0; i < strlen(string); i++){
        if (string[i] < '0' || string[i] > '9'){ //Ocasionaria Em Um Loop Infinito Se O Usuário Não Informar Correto.
            i = -1;
            printf("\nInforme Novamente: ");
            scanf("%[^\n]s", &string);
            getchar();
        }
    }

    // Saiu Do Loop Agora Sim O Valor De string Está correto Agora Só Converter string Em Inteiro E Colocar Em (a) Que É A Nossa Variável Do Tipo Inteiro.

    a = atoi(string); //atoi = Char To Integer
    getchar();
    return 0;
}
    
12.12.2014 / 20:02