Fscanf reading problem in String

I am reading a .txt file. I use fscanf to get data as it is formatted. The line I'm having problems with is this:

result = fscanf(fp, "%s", ap->name);

This is normal until I have a name with a space, for example: St Ives So I use this for reading in white space:

result = fscanf(fp, "%[^\n]s", ap->name);

However, when I try to read the first name (without a space), it just doesn't work and spoils another fscanf.

But I use [^ \ n], it works fine in another file that I use. Not sure what is going on.

If I use fgets instead of fscanf above, I get "\ n" in the variable.

Change //

Ok, so if I use:

result = fscanf(fp, "%s", ap->name);
result = fscanf(fp, "%[^\n]s", ap->name);

This allows me to read a line without spaces. But when I get the "name" with a space, it does not work.

+5
5

:

result = fscanf(fp, "%[^\n]s", ap->name);

, s . %[^\n], : " , , ". s , : " , " s ", , ."

s . , : . , , , . , , .

, : , . , :

result = fscanf(fp, "%[^\n]%*c", ap->name);

%*c , (c), - (*). *, fscanf() , (a char*), , .

%[^\n]\n, , , , . fscanf (, ), , (.. , , [ \t\n]*).

, , . , % [. , ap->name - 256 , :

result = fscanf(fp, "%255[^\n]%*c", ap->name);

; , , fscanf. sprintf, :

char format[256];
snprintf(format, sizeof(format), "%%%d[^\n]%%*c", buffer_size - 1);
result = fscanf(fp, format, ap->name);
+12

Jumm ():

fgets fscanf , "\n" .

:

fgets( ap->name, MAX, fp ) ;
nlptr = strrchr ( ap->name, '\n' ) ;
if( nlptr != 0 )
{
    *nlptr = '\0' ;
}
+2

, [^\n], . [] - , " , , ". ^ . % s fscanf , . fgets sscanf .

0

, , fscanf, , , , - .

%s, , , %s\n, .

pete sake gets , , , 1990 - Morris Worm, fingerd, gets, . , . , , , .

Microsoft gets, , .

EDIT My bad - I did not understand that Clifford really indicated the maximum length for input ... Oops! Sorry Clifford's answer is correct! So, +1 to Clifford.

Thanks to Neil for pointing out my mistake ...

Hope this helps, Regards, Tom.

0
source

I found a problem.

As Paul Tomblin said, I had an additional new character in the box above. Therefore, using what tommieb75 said, I used:

result = fscanf(fp, "%s\n", ap->code);
result = fscanf(fp, "%[^\n]s", ap->name);

And it is fixed!

Thank you for your help.

0
source

All Articles