user2957235
user2957235

Reputation: 55

detecting new line with scanf in C

I have a file consisting of multiple lines. In each line there are several short words. Is there any way to read them with scanf and be able to determine when a new line has started? I could read whole line and then split it, but the problem is I don't know how large can lines be, so i can't create buffer with fixed size. I want to read each word separately.

Upvotes: 1

Views: 2079

Answers (2)

Rontogiannis Aristofanis
Rontogiannis Aristofanis

Reputation: 9073

I couldn't think of a standard way of doing this, so I implemented my own function for reading strings. The function scan(s) returns either EOF, NEW LINE, or NO NEW LINE. Here is the code:

#include <stdio.h>
#include <stdlib.h>

#define NEW_LINE 1
#define NO_NEW_LINE 0
#define MY_EOF -1

int scan(char *s) {
  int c = getchar(), idx = 0;
  while(c == ' ' || c == '\n') c = getchar();
  if(c == EOF) return MY_EOF;
  s[idx++] = c;
  while(c != ' ') {
    c = getchar();
    if(c == EOF) {
      s[idx] = '\0';
      return MY_EOF;
    } else if(c == '\n') {
      s[idx] = '\0';
      return NEW_LINE;
    } else s[idx++] = c;
  }
  s[idx] = '\0';
  return NO_NEW_LINE;
}

int main() {
  freopen("input.txt", "r", stdin);

  char s[500];
  int type;
  do {
    type = scan(s);
    puts(s);
    if(type == NEW_LINE) printf("<New Line>\n");
    fflush(stdout);
  } while(type != MY_EOF);

  return 0;
}

input.txt

1| hello world one two
2| three four
3| a man a plan a canal panama
4| race car
5| blah blah

stdout

 1| hello 
 2| world 
 3| one 
 4| two
 5| <New Line>
 6| three 
 7| four
 8| <New Line>
 9| a 
10| man 
11| a 
12| plan 
13| a 
14| canal 
15| panama
16| <New Line>
17| race 
18| car
19| <New Line>
20| blah 
21| blah

I hope this helps :)

Upvotes: 1

unwind
unwind

Reputation: 400159

If you have POSIX, you can solve this not by going down in abstraction, but by going up to getline().

It's basically a fgets() that handles any length of input line by dynamically allocating it.

Upvotes: 1

Related Questions