Home > other >  Issues with do/while loop ask question too many times
Issues with do/while loop ask question too many times

Time:01-25

I have a problem with my code:
When I write any input different from 1,2,3,4 the output is

Inserire il numero dei giocatori 
inserire un numero valido
Inserire il numero dei giocatori 
inserire un numero valido
Inserire il numero dei giocatori 

How can I fix it?


#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <time.h>

int controll_num(){

    int controll=0;
    int players;
    char c;
    do{
        printf("Inserire il numero dei giocatori \n");
        c=getc(stdin);

        switch (c){

            case 49:
                players=1;
                controll=1;
                break;

            case 50:
                players=2;
                controll=1;
                break;

            case 51:
                players = 3;
                controll=1;
                break;

            case 52:
                players = 4;
                controll=1;
                break;

            default:
                printf("inserire un numero valido\n");
        }
    }while(controll==0);
    return players;
}

int main(){

    controll_num();

    return 0;
}

CodePudding user response:

Instead of getc use scanf as for example

scanf( " %c", &c );

Pay attention to the leading space in the format string. It allows to skip white space characters as for example the new line character '\n' that is placed in the input buffer by pressing the Enter key.

As for getc then it can read white space characters.

Also instead of using magic numbers like 49 as case labels

case 49:

use characters like

case '1':

This will make your code more readable.

CodePudding user response:

You need to check if the value is digit and your switch case is not needed at all.

int controll_num(void){

    int players;
    char c;
    while(1)
    {
        printf("Inserire il numero dei giocatori \n");
        c=getc(stdin);

        if(isdigit((unsigned char)c)) 
        {
            players = c - '0';
            break;
        }
        printf("inserire un numero valido\n");

    };
    return players;
}

int main(void)
{
    printf("Number of players %d\n", controll_num());
}

https://godbolt.org/z/sf7nxE7cx

  • Related