i've been trying to use fscanf to parse parts of a line from a file. The format of each line is like the following:

Connecticut,1788,Hartford,29

I've been trying to use this:

fscanf( fpIn, "%[^,], %d% [^,], %d", name, &year, cap, &popRank )

To extract the state, year, capital, and population rank into the respective fields but it only reads the first two.

And, correct me if i'm wrong, but the the [^,] operation reads everything up to a comma right? According to some of the code snippets i read around here, i'm supposed to place a comma after [^,] but i'm not understanding why I would need to do that.

Thanks for any help you guys could give.

I guess its a typo. You jumbled the positioning of the comma and the percentage sign. Here is the fixed one:

fscanf( fpIn, "%[^,], %d, %[^,], %d", name, &year, cap, &popRank ) ;

Hope it helped, bye.

It would be better to use fgets and sscanf, like

char buff[BUFSIZ];
while ( fgets( buff, sizeof buff, fpIn ) != NULL ) {
  if ( sscanf( buff, "%[^,], %d, %[^,], %d", name, &year, cap, &popRank ) == 4 ) {
    // success, do something
  } else {
    // some error message about a bad line
  }
}

The problem is, if you try to convert and validate at the same time, you get into an awful mess if the fscanf fails, because you then have no idea where in the file you've got to.

In fact, once you've read a line into buff, you can do all sorts of different things in terms of conversion and validation, which would be beyond the scope of fscanf.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.