Reputation: 289
When i am working of with character strings. I have something like this:
#include <stdio.h>
#define MAXLINE 1000
main(){
int c;
int i=0;
char s[MAXLINE];
while(c=(getchar()) !=EOF)
{
s[i] = c;
++i;
}
}
I want to ask after i write something like HELLO
and then hit enter
to break line does the '\n' adds first to after the character stream or the Null terminating character i.e. '\0'
Visually which one is correct representation of what's happening: (1) HELLO\n\0 OR (2) HELLO\0\n
Upvotes: 1
Views: 159
Reputation: 688
Importantly EOF is not equivalent to newline. The loop will terminate only on EOF i.e Ctrl+D (in linux).It will not terminate on pressing enter.
getchar() is a function that reads a character from standard input. EOF is a special character used in C to state that the END OF FILE has been reached.
The return value of getchar() is:
1.On success, the character read is returned (promoted to an int value).
2.The return type is int to accommodate for the special value EOF, which indicates failure:
3.If the standard input was at the end-of-file, the function returns EOF and sets the eof indicator (feof) of stdin.
4.If some other reading error happens, the function also returns EOF, but sets its error indicator (ferror) instead.
So each newline character will be stored in String instead of terminating the loop. And it does not adds any NULL character at the end, so there will be no NULL character. Instead it can be hello\n (where '\n' will be stored as 0x0A in system)
Upvotes: 0
Reputation: 500247
The way your code is written, there is no NUL character added to s
.
Since you are reading the input one character at a time, if you want s
to be NUL-terminated you'll need to add the NUL yourself.
Upvotes: 1