Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
761 views
in Technique[技术] by (71.8m points)

do while - Checking Loop in C - scan() is not running by the second run

void openMenu(int *op) {//edited
    do {
        printf("Your turn...
");
        scanf(" %d", op);
        if (*op > 14 || *op < 1 ) {
            printf("Only enter a number between 1 and 14!
");
        }
    } while (*op > 14 || *op < 1 );
}

I am trying to make a checking loop which controls if the value which was entered is between 1 and 14. If there are letters it has to repeat too, the enter process.

Perhaps it isn't working and everytime it goes in the second run the scanf didn't run.

I checked the thing to set a space in front of the %d, but it isn't working too... Did u have maybe a nice idea?

Working with Xcode on Mac 11.1


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to check the returning value of your scanf:

#include <stdio.h>

 void openMenu(int *op) {//edited
    do {
        printf("Your turn...
");
        if (scanf(" %d", op) != 1 || *op > 14 || *op < 1 ) {
            while(getchar()!='
'); // clean the input buffer
            printf("Only enter a number between 1 and 14!
");
        }
    } while (*op > 14 || *op < 1 );
}       

int main()
{
    int op;
    openMenu(&op);
    printf("Number Read {%d}
", op);
    return 0;
}

A more robust (and complicated) solution would be the following:

int isNumber(char buffer[]){
    for(int i = 0; buffer[i] != ''; i++)
        if(!isdigit((unsigned char) buffer[i]))
           return 0;
    return 1;
}

int readInput(char buffer[]){
    int result = scanf("%99s", buffer); 
    while(getchar()!='
');
    return result;
}

int isInRange(int *op, char buffer[]){
    *op = atoi(buffer);
    return *op <= 14 && *op >= 1;
}
           
           
void openMenu(int *op) {
    do {
        char buffer[100];
        if(readInput(buffer) && isNumber(buffer) && isInRange(op, buffer)) {
           break;
        }
        printf("Only enter a number between 1 and 14!
");
    } while (1);
}         

This would avoid that input such as 4odgjlda would be considered a valid number. Nevertheless, with the current approach inputs such as 4 odgjlda would still be considered as a valid input, since scanf would read the first word and not the entire line. For a more robust solution you should use fgets instead. One can see an example of such solution on the answer provided by Andreas Wenzel.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...