I want to compare some strings, but unfortunately I don't find any proper way to do it.
The idea behind is to ask for a keyboard input, read a variable, one symbol and if it is "y" or "n" ("yes" or "no" apparently) it executes certain activities. If the value of the char is neither of them, the question is asked again, until either of "y" or "n" is not pressed. I don't understand how to implement that.
#include <stdio.h>
#include <string.h>
int main()
{
char answer;
answer='a';
while (answer!='n'&&answer!='y')
{
printf("\nQuestion? (y/n) ");
scanf("%c",&answer);
}
return 0;
}
This actually works pretty nice, but if I don't press 'y' or 'n', the "while" starts again and due to a reason I cannot understand, the "printf" is executed one times more, than the length of the input. So if we run this code and we apply "asdf" as an input (four symbols) the "printf" in the "while" is displayed five (four plus one) times. The result is:
Question? (y/n)
Question? (y/n)
Question? (y/n)
Question? (y/n)
Question? (y/n)
Everything else works really nice in my code, but this... Obviously, this is not the best way to approach. I have also tried "strcmp()":
#include <stdio.h>
#include <string.h>
int main()
{
char answer='a';
while (strcmp(answer,'n')!=0&&strcmp(answer,'y')!=0)
{
printf("Question?");
scanf("%c",&answer);
}
return 0;
}
I don't know why, but the program doesn't even start. It is clear, that I haven't implemented "strcmp" properly and I don't understand what is wrong.
Any ideas, what should I do, so I can avoid multiple execution of the "printf" in the "while" or to make "strcmp" work the way I demand it to?