Write a program that receives random characters and outputs them repeatedly. However, if you enter (Q), the program ends.
Enter one character: A
Characters entered: A
Enter one character: d
Characters entered: d
Enter one character: Q
That's the question.
char ch;
while (ch != 'Q')
{
printf("Enter one character: ");
scanf("%c", &ch);
printf("Type: %c\n", ch);
}
return 0;
}
This is the code I made, but there is an error. Help me.
c scanf
#include <stdio.h>
int main()
{
char = NULL; // Initialize variable ch NULL to receive characters
while(1)
{
printf("Enter one character: ");
ch = getchar();
fflush(stdin); // Empty input buffer
if(ch!='Q') printf("Type: %c\n\n",ch); // if not chQ
else break; // escape repeat if ch is Q
}
return 0;
}
Based on the question you gave me, I rewritten the code considering that the output value is correct.
And the reason why the error occurred in the code you posted was because the relationship was calculated in the while repetition statement when the variable ch was declared and not defined (that is, the initial value was not given and the garbage value was included)
So in my code, I initialized it by putting NULL value in the ch variable.
© 2024 OneMinuteCode. All rights reserved.