scanf
is the wrong tool for this job (as for most jobs). If you are required to use this function, read one char
at a time with scanf("%c", &c)
.
You code misuses scanf()
: you are passing arr
, the address of an array of pointers to char
instead of an array of char
.
You should allocate an array of char
with malloc
, read characters into it and use realloc
to extend it when it is too small, until you get a '\n'
or EOF
.
If you can rewind stdin
, you can first compute the number of chars to read with scanf("%*s%n", &n);
, then allocate the destination array to n+1
bytes, rewind(stdin);
and re-read the string into the buffer with scanf("%s", buf);
.
It is risky business as some streams such as console input cannot be rewinded.
For example:
fpos_t pos;
int n = 0;
char *buf;
fgetpos(stdin, &pos);
scanf("%*[^\n]%n", &n);
fsetpos(stdin, &pos);
buf = calloc(n+1, 1);
scanf("%[^\n]", buf);
Since you are supposed to know just some basic C
, I doubt this solution is what is expected from you, but I cannot think of any other way to read an unbounded string in one step using standard C.
If you are using the glibc and may use extensions, you can do this:
scanf("%a[^\n]", &buf);
PS: all error checking and handling is purposely ignored, but should be handled in you actual assignment.