multiline input reading input from stdin in C
Hello every one I want to ask that is there a way in c programming through which I can开发者_JAVA技巧 read multi line input from stdin
as I cant use scanf() also not fgets as it take input till /n
and also how to stop the input like some delimiter
thanks alot
also I am not using c++
Use fread
.
eg, copied from the link
#include <stdio.h>
...
size_t bytes_read;
char buf[100];
FILE *fp;
...
bytes_read = fread(buf, sizeof(buf), 1, fp);
...
I recommend you read input one character at a time with getc
, look for whatever delimiter you want, and append the non-delimiter characters to a buffer whose size you control manually (with realloc
). The alternative is to read large blocks with fread
and scan for the delimiters, but the getc
approach is likely to be easier and simpler.
Make sure to look for EOF
as well as your explicit delimiters.
This task would be pretty simple if there were a proper string datatype in C, with automatic memory management. The idea is:
string s = str_new();
const char *delimiter = "EOF\n";
while (true) {
int c = fgetc(f);
if (c == EOF) {
break;
}
str_appendc(s, c);
if (str_endswith(s, delimiter)) {
str_setlen(s, str_len(s) - strlen(delimiter));
break;
}
}
You just have to write the proper functions for the string handling.
精彩评论