James Green
James Green

Reputation: 125

Reading formatted file containing different types

I'm trying to read from a file with the format:

12,6:23.4

I need to collect the 12, 6 and 23.4 separately but I can't seem to get around the comma and colon.

Here is my attempt:

int x = fscanf(fp, "%d %[^,] %d %s %f", &int_var, comma_buffer, &int_var_2, colon_buffer, &float_var);

But I get garbage outputs like:

int_var_1: 12

Comma_buffer: ��#� 

int_var_2:  0.000000 

colon buffer: , 

float_var: 0.000000

Upvotes: 1

Views: 31

Answers (1)

chux
chux

Reputation: 153498

Use ',' and ':' in the format such as "%d,%d:%f". Consider a preceding space to tolerate optional white-space before the fixed character: "%d ,%d :%f".


The best way to read a line from a file is fgets(), then parse.

Consider using " %n" to detect trailing junk.

#define LINE_SZ 100
char buf[LINE_SZ];

if (fgets(buf, sizeof buf, fp)) {
  int n = 0;
  sscanf(buf, "%d ,%d :%f %n", &int_var, &int_var_2, &float_var, &n);
  if (n == 0 || buf[n]) {
    puts("failed to parse all or extra junk.");
  } else {
    printf("%d,%d:%f\n", int_var, int_var_2, float_var);
  }
}

Both "%[^,]" and "%s" should never be used as they lack a width, something robust code always use.

Upvotes: 2

Related Questions