I am trying to create a program that compares the letter a user inputs to my letter. If the letters are the same, the program should say that they are the same, then terminate. If they are not the same, then the user should be prompted to enter another character until they guess it correctly.
I have tried nesting an if statement and nesting a while loop to achieve the case where the letters are equal.
#include <stdio.h>
int main()
{
char myLetter = 'a';
printf("insert a char:");
char userLetter;
scanf("%1s", &userLetter);
while (userLetter != myLetter)
{
printf("%c does not match mine, try again:", userLetter);
scanf("%1s", &userLetter);
}
while (userLetter == myLetter)
{
printf("char matches! program will terminate now. ");
break;
}
}
expected:
insert a char:h
h does not match mine, try again:j
j does not match mine, try again:g
g does not match mine, try again:f
f does not match mine, try again:a
char matches! program will terminate now.
actual:
insert a char:h
h does not match mine, try again:j
j does not match mine, try again:g
g does not match mine, try again:f
f does not match mine, try again:a
a does not match mine, try again:a does not match mine, try again:^C
The proper format operator for reading a single character is %c
, not %1s
. The latter reads a single character, but writes it into a null-terminated string, so it will write a null byte outside the userLetter
variable, which causes undefined behavior.
You should put a space before the operator to make scanf
skip over whitespace before reading the character. This is needed to make it ignore the newline after each response.
You should also turn off output buffering or flush the buffer after each prompt, since they don't end with a newline.
There's no need for the while
loop at the end, since you don't get out of the first loop until the characters match.
This is a working version:
#include <stdio.h>
int main()
{
char myLetter = 'a';
setbuf(stdout, NULL);
printf("insert a char:");
char userLetter;
scanf(" %c", &userLetter);
while (userLetter != myLetter)
{
printf("%c does not match mine, try again:", userLetter);
scanf(" %c", &userLetter);
}
printf("char matches! program will terminate now.\n");
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments