I’m a beginner in C ,so please forgive me if this question is stupid or was asking weirdly.
I’m reading C primer plus and one of the examples in Chapter-8 is some loop that testing whether the user entered – a newline character or not ,which I couldn’t understand.
The code is short so I will show it to you:
int main(void)
{
int ch; /* character to be printed */
int rows, cols; /* number of rows and columns */
printf("Enter a character and two integers:\n");
while ((ch = getchar()) != '\n')
{
if (scanf("%d %d",&rows, &cols) != 2)
break;
display(ch, rows, cols);
while (getchar() != '\n')
continue;
printf("Enter another character and two integers;\n");
printf("Enter a newline to quit.\n");
}
printf("Bye.\n");
return 0;
}
void display(char cr, int lines, int width) // the function to preform the printing of the arguments being passed
What i dont understand is right here:
while (getchar() != '\n')
continue;
printf("Enter another character and two integers;\n");
printf("Enter a newline to quit.\n");
First of all, the while (getchar() != '\n') is testing the first ch was entered right?
Second, if that is true, how come the continue is not skiping the printf statements and going to the first while? isn’t it what it should do?
Tnx
Because there are no braces after the
whilestatement, only the very next line is included in the loop. So,continuecontinues the while loop until a new line character is found and then the execution continues to theprintfstatements.It is equivalent to this: