Do we also have to initialize \0(NULL) character?
Code:
char S[N];
for (i = 0; i < N; ++i) {
scanf("%c", & S[i]); //Is it a wrong way to initialize char string character by character?
}
for (i = 0; i < N; ++i) {
printf("%d %c", i, S[i]);
}
This should work, and you don't have to add the NUL (not NULL, it's ASCII) at the end because you're treating it as an array of N distinct characters and not as a string. If you wanted to printf it with %s or call strlen on it, then you'd have to add the NUL (and allocate N+1 characters for the array).
You should add \n at the end of your printf format string.
Note that you will have to type the N characters all on one line. If you press return after the first one, for example, the linefeed will be taken as the second character.
\0 at the end. So to store "hello" you need char[6].Your code should work as long as there is enough data to be read from stdin. You should test the return value of scanf() to detect premature end of file. The output will be concatenated on a single line because you did not put a newline at the end of the format string.
Here is a much simpler way with fread:
#include <stdio.h>
int main() {
#define N 100;
char S[N];
int n = fread(S, 1, N, stdin);
if (n < N) {
printf("read error: only %d bytes read\n", n);
}
for (int i = 0; i < n; ++i) {
printf("%d %c\n", i, S[i]);
}
return 0;
}
scanf, but if you actually want to read characters into an array, this is obviously a better approach.If you need to initialize a character array, write: char S[N] = {0}; -- it will be initialized with zero characters, that could be used as a string terminator if you need them to.
If you need to read a string, just do that with fread(buf, 1, N, stdin);
All in all, your code might look like this:
char S[N] = {0};
fread(buf, 1, N, stdin);
\nat the end of the printf format string