mainajaved
mainajaved

Reputation: 8173

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 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++

Upvotes: 1

Views: 3448

Answers (3)

Roland Illig
Roland Illig

Reputation: 41625

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.

Upvotes: 0

zwol
zwol

Reputation: 140569

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.

Upvotes: 1

pmg
pmg

Reputation: 108988

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);
...

Upvotes: 1

Related Questions