Adrian
Adrian

Reputation: 11

What is this sscanf doing?

The code I'm working on is opening an uninitialized file and scanning in the following variables. I'm trying to figure out what it's doing, but I don't understand what the FSYM and ISYM formatting (?) is trying to do, other than perhaps declaring them as float or int strings.

sscanf(line, "%"ISYM" %"ISYM" %"ISYM" %"FSYM" %"FSYM" %"FSYM" %"FSYM" %"FSYM,
   &idummy, // nt   - skip
   &idummy, // l    - skip
   &idummy, // lev  - skip
   rad+nl,  // x    = radial coordinate
   vel+nl,  // xdot = radial velocity
   den+nl,  // rho  = density
   &dummy,  // tev  - skip temperature (eV)
   pre+nl   // p    = pressure
   );

line is the first line the opened file, which is then scanned in to the variables. Any ideas as to what's happening?

Upvotes: 0

Views: 163

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254451

Presumably, they are macros defined somewhere in your code, which expand to string literals containing the necessary specifiers for a scanf string. They would be something like

#define ISYM "d" // integer symbol for scanf
#define FSYM "f" // floating-point symbol for scanf

so that after expansion the argument becomes

"%""d"" %""d"" %""d"" %""f"" %""f"" %""f"" %""f"" %""f"

and, since consecutive string literals are joined to make a single string, this is equivalent to

"%d %d %d %f %f %f %f %f"

This might be useful if you might want to change the types:

#ifdef BIG_TYPES
    typedef long   i_type;
    typedef double f_type;
    #define ISYM "ld"
    #define FSYM "lf"
#else
    typedef int   i_type;
    typedef float f_type;
    #define ISYM "d"
    #define FSYM "f"
#endif

Of course, C++ has type-safe I/O to avoid all this nonsense:

std::istringstream ss(line);
ss >> idummy;
// and so on

Upvotes: 7

Steve Sanbeg
Steve Sanbeg

Reputation: 887

That's preprocessor string concatenation. They must be defined as strings somewhere else; when cpp hits multiple adjacent strings it concatenates them together, so the code is using the preprocessor to build a longer string from predefined parts.

Upvotes: 1

Related Questions