Reputation: 371
I have trouble finishing a while loop using '\0'
in c programming language, the c code is the following
#include<stdio.h>
char r;
int main()
{
do
{
scanf("%c", &r );
printf("%c", r);
}
while (r!='\0');
return 0;
}
My problem is that the program never finishes at the final character of typed string line, the while loop is always in waiting mode because of the scanf
and never go to return 0
. I do not know why this happen.
The output of this program is like this:
1234
2345
4556
7788
2345, 4556, 7788
Those are numbers I typed, but the program never finish (never go to return 0
), I want to print just one string and I want the program ends.
Upvotes: 0
Views: 1426
Reputation: 153348
Typical user input is a line, a sequence of characters up to and including a final '\n'
.
As a part of user input, '\0'
is just another character. It is often difficult to key in. Some keyboards allow it with CtrlShift@ or other ways @user3629249
Very rarely is a string (a sequence of characters up to and including a final '\0'
) used on input.
To handle user input, a simply approach is to use fgets()
to read a line of user input. That input will be saved as a string by fgets(buf)
by appending a null character '\0'
to the characters read: all saved in buf
.
#include<stdio.h>
int main(void) {
char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) {
puts("End-of-file or error encountered");
} else {
// maybe lop off the potential trailing \n from buf
buf[strcspn(buf, "\n")] = '\0';
printf("User input was <%s>\n", buf);
}
return 0;
}
To end user input, the usual approach is to signal the "end-of-file", see recognise return as EOF on the console
If code must use scanf();
, check the return value to detect end-of-file or input error. @user3629249
if (scanf("%c", &r ) != 1) {
puts("End-of-file or error encountered");
}
Upvotes: 2