How to read one whole line from text file using <

妖精的绣舞 提交于 2020-01-05 06:56:28

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/41861208/how-to-read-one-whole-line-from-text-file-using

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!