Reputation: 510
I am attempting to check for "y" or "n" and if the input is outside of that continue to ask the user to re-enter their response.
What I currently have:
do{
printf("Press 'y' to go again or 'n' to quit: ");
scanf("%s", goAgain);
result = strncmp(goAgain, yes, 1);
result2 = strncmp(goAgain, no, 1);
printf("%d %d\n", result, result2);
}while(result != 0 || result2 != 0);
I know this isn't efficient, I've been trying random things while debugging. In this setup the yes and no are both char * variables. yes contains "y" and no contains "n"
The output of the last printf gave me 0 for result and 11 for result2. This should have dropped out of the do while since I used an OR. Am I doing something obviously stupid or is there some quirk of C that I ma missing (also...this is the first C program I have written so please explain a bit on any C specific suggestions)
Thanks
Edit: Thanks for the replies....that was a rather stupid mistake I should have caught. Now, is there a better way of doing this? The way I have currently feels really clunky, and I don't see any way to make it all that much less clunky (other than directly moving the strncmp's into the while statement)
Upvotes: 1
Views: 88
Reputation: 40155
char goAgain;
while(1){
printf("hello\n");
do{
printf("\nPress 'y' to go again or 'n' to quit: ");
}while(scanf(" %c", &goAgain) == 1 && goAgain != 'y' && goAgain != 'n');
if(goAgain == 'n')//there is no need to check for 'y'
break;
}
Upvotes: 0
Reputation: 964
strncmp(str1,str2,num) function returns an integral value indicating the relationship between the strings:
Upvotes: 1
Reputation: 994937
If result
is 0 and result2
is 11, then
result != 0 || result2 != 0
0 != 0 || 11 != 0
false || true
true
which means the while
loop will continue looping.
Upvotes: 2