开发者

multiline input reading input from stdin in C

开发者 https://www.devze.com 2023-04-12 14:50 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消