开发者

Press enter to continue after yes/no in C

New programmer here with only some minor Java experience trying my hand at writing something in C. I want to ask someone a Yes/No question, do something depending on their answer, then ask them to press Enter to continue. I'm having two problems:

1.) I can't get the program to accept 'y', 'Y', or "Yes" as answers. I can get it to accept one, but not all three. The "logical OR" operator || isn't working. 2.) I can't get it to stop at "Press Enter to Continue" without two "Flush" commands of:

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

The code I have and am trying to use is as follows:

int main (int argc, const char * argv[]) {
    printf("Would you like to continue? Please press y or n.\n");

    if(getchar() == 'y'){
        printf("You pressed yes! Continuing...");
    }
    else{
        printf("Pressed no instead of yes.");
    }
        //flush commands go here
    printf("\nPress ENTER to continue...");
    if(getchar()=='\n'){
        printf("\nGood work!");
    }else{
        printf("Didn't hit ENTER...");

    return 0;
}

Any help would b开发者_运维知识库e appreciated, thanks.


Assuming that you are working in *nix environment, You can create a buffer to store the incoming characters one after the other. You have two cases:

1. Single character input
2. 3 character String

For all other cases you can blindly say that the input is not OK!
For case 1, i should be 1 and the character should be 'y' or 'Y'
For case 2, i should be 3 and the string should be 'Yes'
Any other case is incorrect. Here is the code:

#include<stdio.h>
int main()
{
char ch[3];
char c;
int i=0;
while(((c=getchar())!='\n')){
        ch[i]=c;
        i++;
}
ch[i]='\0';
if (i==1)
        if (ch[0]=='Y'||ch[0]=='y')
                printf("OK");
        else
                printf("Not OK");
else if(i==3)
        if (strcmp(ch,"Yes")==0)
                printf("OK");
        else
                printf("Not OK");
else
        printf("NOT OK");
return 0;
}

I would recommend using something like this.


First off you might like to save the result of the first getchar() to test each possible value eg

int c=getchar();
if(c=='y' || c=='Y')
....

The reason the "enter" part skips for the second test is because when you type 'y' or 'n' you press enter after to send your input - the \n is still in the buffer and it pulled by the next call to getchar()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜