Reputation: 1144
I'm getting a string from the keyboard, in C and Linux (Ubuntu 14.04):
char string[STR];
fgets(string, STR, stdin);
And I've noticed that strlen()
is not working.
So, I've decided to do the following:
int i = 0;
while (string[i] != '\0') {
printf("\nchar: %c\n", string[i]);
i++;
}
printf("\nFinished");
I type "hello"
as input, and the output is the following:
char: h
char: e
char: l
char: l
char: o
char:
"Finished"
is never printed.
I can't see which is the problem. I suspect it's because the input read from keyboard doesn't have '\0'
terminated?
Yesterday I was working with Windows, and was working fine with strings.
EDIT: STR is defined as 128.
Upvotes: 0
Views: 117
Reputation: 6457
1.If STR
's values is smaller than the input string's (length + termination character: '\0'), the last character of your input string isn't stored in char string[STR]
;. The function strlen()
uses '\0'
to determine the end of the string, that is why without it, it "doesn't work" and your program runs in an infinite loop.
2.Buffering may be the other cause, as @l3x perfectly explains.
Upvotes: 1
Reputation: 108978
Yes it does. fgets()
stores a '\0'
as the last byte written (may not be the last position in the array).
You need to check the return value of fgets()
and most functions with a prototype in <stdio.h>
.
char x[100]; // unitialized, x[99] may be anything
if (!fgets(x, sizeof x, stdin)) /* error; contents of x are not trustworthy */;
x[strlen(x)] == '\0'; // true, always true
// provided the previous statement did not generate an error
Upvotes: 1
Reputation: 121377
From the code snippets you posted, there's no obvious problem. My guess is that this is part of a larger program and what you observe is due to a output buffering. The standard output stream is typically line buffered and will be flushed periodically (as the buffer becomes full).
So adding \n
at the end of printf might fix it if stdout
is attached to a terminal device. If you are redirecting it to a file (./a.out >output
) then this won't fix it either. So try calling fflush()
:
fflush(stdout);
after the printf call.
I say "part of larger program" because at the end of normal process termination, all the buffered output will be flushed. So there wouldn't be any need for manual flushing. On abnormal process termination, the buffered output may be lost.
Another way is to disable the stdout
buffering completely using sebtuf()
:
setbuf(stdout, 0);
Upvotes: 4