How to use fscanf to read any character in a string until the tab is reached?

How to use fscanf to read any character in a string before reaching a tab?

My data file has only 1 line:

123'\t'(Tab)345'\t'Le Duc Huy'\t'567

and I use fscanf as follows:

fscanf(fin,"%d %d %d %[^\t]%s %d",&m,&n,&k,s,&q);

it returns q with the wrong value. Can anyone tell me what made this unsuccessful?

+3
source share
5 answers

Using fscanf(), you will need a negative character class and length:

char string[32];

if (fscanf(fp, "%31[^\t]", string) != 1)
    ...error or EOF...

, , q undefined. , fscanf(), , , , , , , , 4 5, , .

+2

fscanf fgetc ( ):

int c;
string s = "";
for (;;)
{
    c = fgetc(somefile);
    if (c == '\t' || c == EOF) break;
    s += c;
    // ...
}
+1

fscanf() :

fscanf (stream, "[^\t]", output);
0

, !


char foo[100];
scanf("%s\t", foo);

0

Clear the space before %[. He is eating your tab. Also, as others have said, this code is unsafe and probably unreliable on input that is not formatted exactly as you would expect. It would be better to use fgetsand then analyze it yourself using strtoland a few for loops.

0
source

Source: https://habr.com/ru/post/1777694/


All Articles