Since scanf()
returns **the number of elements successfully read, you must find a way to make it fail to read the %s
. One common practice is to end the input with EOF, which is Ctrl-Z
then Enter
in Windows console, and Ctrl-D
on a Unix terminal. After reading EOF scanf()
will return EOF
which is of course not 1, then the loop exits normally.
Alternatively, you can use a custom terminating string in your code:
char input[1000];
while (scanf("%s", input) == 1) {
if (strcmp(input, "end") == 0) {
// End the loop
break;
}
printf("%s\n", input);
}