3

I am trying to get one whole line from some text file instead of one word until it meets white space, here is source code:

#include <stdio.h>

void main() {
  int lineNum=0;
  char lineContent[100];

  scanf("%s", &lineContent);
  printf("%s\n", lineContent);
}

And here is my text file, called test.txt, content containing 2 lines:

111 John Smith 100 98 1.2 2.5 3.6
222 Bob  Smith 90 91 3.2 6.5 9.6

And I run it with following command:

a.out < test.txt

My output is just:

111

What I want is:

111 John Smith 100 98 1.2 2.5 3.6

Of course, I can simply use while statement and read recursively until it meets EOF, but that is not what I want. I just want to read one whole line per each time I read from file.

How can I do this?

Thank you very much.

DYZ
  • 55,249
  • 10
  • 64
  • 93
online.0227
  • 640
  • 4
  • 15
  • 29
  • 3
    (1) Use `fgets` : `scanf("%s", &lineContent); printf("%s\n", lineContent);` --> `fgets(lineContent, sizeof lineContent, stdin); printf("%s", lineContent);`. Also `while(fgets(...) != NULL) fputs(lineContent, stdout);` – BLUEPIXY Jan 25 '17 at 20:39
  • 2
    (2) `scanf("%s", &lineContent);` --> `scanf("%99[^\n]%*c", lineContent);`. Also `while(1==scanf("%99[^\n]%*c", lineContent)) printf("%s\n", lineContent);` – BLUEPIXY Jan 25 '17 at 20:42

2 Answers2

5

fgets() is the most convenient standard library function for reading files one line at a time. GNU getline() is even more convenient, but it is non-standard.

If you want to use scanf(), however, then you can do so by using the [ field descriptor instead of s:

char lineContent[100];

scanf("%99[^\n]", &lineContent);
getchar();

Note the use of an explicit field width to protect against overrunning the bounds of lineContent in the event that a long line is encountered. Note also that the [ descriptor differs from s in that [ does not skip leading whitespace. If preserving leading whitespace is important to you, then scanf with an s field is a non-starter.

The getchar() reads the terminating newline, presuming that there is one, and that scanf() did not read 99 characters without reaching the end of the line.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
1

If you want to read line by line, then use fgets() or getline() (available on POSIX systems) instead of scanf(). scanf() stops at first whitespace (or matching failure) for %s.

P.P
  • 117,907
  • 20
  • 175
  • 238