C getchar() doesn't wait for input/ conditional loop doesn't int

泄露秘密 提交于 2019-12-25 06:38:04

问题


I am trying to add a feature to my C console application calculator that prompts the user to decide whether they want to perform another calculation using: y or n, but in testing, getchar() refuses to wait for input and the program proceeds as though it has received valid input. The following is a minimal example of the feature:

main()
{
    char newCalculation;

    do{
        lengthFormula(); /* main calculation formula */
        printf("Would you like to do another calculation? (Y/N)");
        newCalculation = getchar();

    }while(tolower( newCalculation ) == 'y');

    if(tolower(newCalculation) == 'n'){
        exitProgram(); /* exit the program */
    }

    while(tolower(newCalculation) != 'n' && tolower(newCalculation) != 'y'){
        printf("This is not a valid response.\n Please enter \"Y\" 
                if you want to do another calculation, 
                or enter \"N\" to exit.\n");
        newCalculation = getchar();
    }
    return 0;
}

When I run this, the program does not wait for input after:

Would you like to do another calculation? (Y/N)

, but instead proceeds as though it has received invalid input. The result is that it spits out the prompt and the invalid input notice one after the other without a space:

Would you like to do another calculation? (Y/N)

This is not a valid response.

Please enter \"Y\" if you want to do another calculation, or enter \"N\" to exit.

If I enter a "y" after this, main() returns 0 and the program terminates.

Is someone able to see where I went wrong here? Why won't the console wait for input at getchar()? Why does valid input terminate the program after the first invalid response?

P.S.: Please don't tell me to "read a book" or shoo me away to Dennis Ritchie or one of the previous SO discussions on input. I've been poring over Richie's discussion of I/O, as well as similar texts from Lynda.com and Wiley, and none of the previous "it won't wait for input" posts addresses my issue as far as I can tell.

@simplicisveritatis Here is the modification of your code that I tried. Still have the same getchar issues.

int main(void)
{
    /* local variable declaration */
    char newCalculation = 'y';

    /* main function */
    /*if(tolower( newCalculation ) == 'y')
    {
        lengthFormula(newCalculation);
    }*/
    do
    {
        lengthFormula();

        printf("Would you like to do another calculation? (Y/N)");
        newCalculation = getchar();

        if( tolower( newCalculation ) == 'n' )
        {
            exitProgram();
        }

        while( tolower( newCalculation ) != 'n' && tolower( newCalculation ) != 'y' )
        {
            printf("This is not a valid response.\n Please enter \"Y\" if you want to do another calculation, or enter \"N\" to exit.\n");
            newCalculation = getchar();
        }
    }while( tolower( newCalculation ) == 'y' );
    return 0;
}

回答1:


Your code has a lot of problems: main should be:

int main(void){return 0;}

You need to cast getchar (read about getchar) and should be:

newCalculation = (char)getchar();

Your approach on do{}while; + while{} is also wrong used.

Try the following:

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

int main(void){
    int     validate;
    char    menu_choice;
    validate = 0;

    do{
        printf("Would you like another go?(y/n):\t" );

        if(scanf(" %c", &menu_choice ) == 1){
            if((menu_choice=='y') || (menu_choice=='Y')){
                printf("You choosed Yes\n\n\n");
                validate = 1;
            }else if((menu_choice=='n') || (menu_choice=='N')){
                printf("You choosed No\n\n\n");
                validate = 2;
            }else{
                printf("Wrong Input.\n\n\n");
                validate = 0;
            }
        }
    }while( validate == 0 || validate == 1);

    printf("Goodbye\n");
    return 0;
}



回答2:


Include your three cases: exit condition, wrong input and calculate within the while loop:

main(){
do{
    printf("Would you like to do another calculation? (Y/N)");
    // get input
    char newCalculation;
    newCalculation = getchar();

    // exit condition
    if(tolower(newCalculation) == 'n'){
        exitProgram(); /* exit the program */
    }
    // wrong input condition
    else if(tolower(newCalculation) != 'n' && tolower(newCalculation) != 'y'){
        printf("This is not a valid response.\n Please enter \"Y\" 
            if you want to do another calculation, 
            or enter \"N\" to exit.\n");
       // you should clear the input stream from the wrong input
    } 
    else{
        // calculate  
        lengthFormula();  
     }
}while(tolower(newCalculation) == 'y');

return 0;
}



回答3:


Why won't the console wait for input at getchar()?

Most probably, your function lengthFormula() reads input (e. g. by using scanf() or whatever), but doesn't read the line ending character \n from the input buffer. Then after returning from lengthFormula(), the getchar() has to read remaining content from the input buffer rather than requesting fresh input.

Why does valid input terminate the program after the first invalid response?

That's because your

    while(tolower(newCalculation) != 'n' && tolower(newCalculation) != 'y')

does the same after a response of y as after a response of n - it leaves the loop and gets to the following

    return 0;


来源:https://stackoverflow.com/questions/32671751/c-getchar-doesnt-wait-for-input-conditional-loop-doesnt-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!