I want to take a line of string in C. How to do that? if I use format specifier %s in printf, it would only take characters upto first whitespace.How to get rid of it? is there any other way except using getline? Thanks in advance.
1 Answer
scanf is a poor choice for getting lines out of an input stream. While you can do it quite easily:
buf[SIZE];
scanf ("%[^\n]\n", buf);
You will be at the risk of being subject to a buffer overflow error/attack.
The better way is to read 'SIZE' characters at a time using fgets, and copying the data into a dynamically allocated buffer that you can resize upon filling it up:
buf[SIZE];
do {
fgets (buf, SIZE, stdin);
/* Handle copying to dynamic buffer and resize over here */
} while (/*check we haven't reached eol*/);
1 Comment
chux
"%[^\n]\n" gives the impression that after getting text before the EOL, the EOL (and only the EOL is consumed). Instead EOL and all the following whitespace is consumed. Alternative idea "%[^\n]%*c". But as you suggest
fgets() is the way to go.
_sversion being optional. Seemed likefgetswith one less argument, but if it's optional, meh. en.cppreference.com/w/c/io/fgets