I can read file contents from stdin
with scanf("%s", &input)
.
How much space should I be allocating for the input
string if I do not know how long the file will be?
Consider using fgets
instead of scanf
. scanf
can cause overflow, but you can tell to fgets
the maximum size you want to read. If you need scanf
for the format scanning, you can still use sscanf
after fgets
.
char * fgets ( char * str, int num, FILE * stream );
You should reverse the question. You allocate a buffer of a defined size and them limit the input, be it with scanf
of fgets
.
#define SIZE 256
char buf[SIZE];
fgets(buf, SIZE, stdin);
or
scanf("%255s", buf);
and then iterate reading.
The use of fgets
instead of scanf
depends if your input is line oriented or space separated. And ... RTFM ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.