Can fscanf () read spaces?

I already have code to read a text file with fscanf(), and now I need to change it so that fields that were previously free of spaces should allow spaces. The text file is mainly in the form:

title: DATA
name: DATA
etc ...

which is mostly parsed using fgets(inputLine, 512, inputFile); sscanf(inputLine, "%*s %s", &data);reading DATA fields and ignoring headers, but now some data fields should contain spaces. I still need to ignore the title and the space immediately after it, but then read the rest of the line, including spaces.

Is there any way to do this with a function sscanf()?

If not, what is the minimum change I can make to the code to handle spaces correctly?

UPDATE: I edited the question to replace fscanf () with fgets () + sscanf (), which is what my code uses. I really didn't think this was relevant when I first wrote the question, so I simplified it to fscanf ().

+5
source share
6 answers

If you cannot use fgets(), use the conversion specifier %[(with the exclude option):

char buf[100];
fscanf(stdin, "%*s %99[^\n]", buf);
printf("value read: [%s]\n", buf);

But fgets()better.


Edit: version with fgets()+sscanf()

char buf[100], title[100];
fgets(buf, sizeof buf, stdin); /* expect string like "title: TITLE WITH SPACES" */
sscanf(buf, "%*s %99[^\n]", title);
+11
source

I strongly recommend that you stop using fscanf()and start using fgets()(which reads the whole line), and then parse the read line.

- .

+3

scanf , , :

scanf("%*s %[^\n]", str);

, , , , , , str ( scanf ). , , , .

, , , - fgetc char char, , , , , , .

+3

-

fscanf("%*s");

, fgets:

fgets(str, stringSize, filePtr);
+2

A %s specifier fscanf , .

, %[^\n] . , '' . ,

fscanf("%*s %[^\n]", &str);

( "title:" ) , , newline str, , .

, str -

fscanf("%*s %100[^\n]", &str)

, (100 , NUL ).

+2

, *scanf. Dave Hanson C . Icon, , , sscanf , , , . , , , .

+1

All Articles