Scanning characters and integers at the same time

I feel like an idiot, as Aconcagua solved my issue. I forgot the ampersand, and once I put it in there, the %s works for reading both char and int (something I didn't know)! Thanks all who offered help!

I have an input file for an assignment that has chemical formulas that need to be scanned in and printed (ex. SO). I am using a structure to read in the data as it is accompanied by a series of floating point numbers that are used in calculations. How would I declare the variable and scan that piece of data? I tried declaring as both char and unsigned char while using %s to try to read it in.

for(i = 0; i <= control - 1; i++)
    fscanf(table,"%s %lf %lf %lf %lf", gases[i].gas, gases[i].coefa,
           gases[i].coefb, gases[i].coefc, gases[i].coefd);

Input file:

12 6
SO2 3.891e1   3.904e-2   -3.105e-5   8.606e-9
SO3  4.85e1   9.188e-2   -8.540e-5   32.40e-9
O2   2.91e1   1.158e-2  -0.6076e-5   1.311e-9
N2   2.90e1  0.2199e-2  -0.5723e-5  -2.871e-9

1 answer

  • answered 2018-11-08 05:47 user1118321

    In general, in C++ you shouldn't be using fscanf(). You should be using file streams. So your example would probably look something like this:

    ifstream inputFile("path to input file");
    //... other code
    for (i = 0; i <= control -  1; i++)
        inputFile >> gases[i].gas;
        inputFile >> gases[i].coefa;
        inputFile >> gases[i].coefb;
        inputFile >> gases[i].coefc;
        inputFile >> gases[i].coefd;

    This should get the proper types if you've declared the various members of whatever type gases is to be the same types as the data in the file. In this case, it looks like gas would be a std::string, and the coefficients would be either float or double.