0

I want to read a text from the input in a line by line manner, and not read any line that starts with 'a', then store the remaining text in an array. I am not sure how to do this since my program terminates reading just the first line of the text. Lets say the text is:

hello world \n a hello world \n hello world'

Then my output should be:

hello world \n hello world

char line[1000];
int line_len = 0;
while ((c = getchar()) != '\n'){   
     line[line_len++] = c;
}
return 0;
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49

1 Answers1

2

perhaps using getline might be easier:

char *line = NULL;
size_t len = 0;
ssize_t nread;

while ((nread = getline(&line, &len, stdin)) != -1) {
    if (nread == 0 || line[0] != 'a') {
        printf("Got a valid line: %s", line);
    }
}

free(line);
IronMan
  • 1,854
  • 10
  • 7
  • might want `line[strspn(line, " \t")] != 'a'` to test if the first non-space or tab character is an `a` -- the example text and output looks like it has space there. – Chris Dodd Sep 17 '19 at 01:39
  • Also, the `nread == 0` test is pointless (it will never be true) as `getline` can never return 0. – Chris Dodd Sep 17 '19 at 01:44
  • I recommend checking that `line` is not NULL before calling `free` unless your memory allocator does that for you. – bruceg Sep 17 '19 at 22:30