Scanning characters and integers at the same time

992 views c++
-2

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);
}

Any help would be much appreciated.

4

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

That's the input file (sorry about my formatting, I'm not too sure how to use the site)

answered question

Do you want all the 118 elements to be parsed? If so, the answer would become very broad... So you should consider telling us the limit...

Just a matter of style: With integers, i <= n - 1and i < n are equivalent, the latter reads easier, though...

Are you aware that you need to pass pointers to scanf function family? Assuming coefX members are doubles, you need to pass them as &gases[i].coefX (note the leading ampersand!).

1 Answer

4

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.

posted this

Have an answer?

JD

Please login first before posting an answer.