问题
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