C++ won't read in scientific notation data from a .txt file

5.1k views Asked by At

I am writing a program which is reading in an array from a text file which has both normal integers, and also multiple numbers that are in scientific notation, of the form: #.#####E##. Here is a few sample lines of the input .txt file:

       21   -1    0    0  501  502  0.00000000000E+00  0.00000000000E+00  0.17700026409E+03  0.17700026409E+03  0.00000000000E+00 0. -1.
       21   -1    0    0  502  503  0.00000000000E+00  0.00000000000E+00 -0.45779372796E+03  0.45779372796E+03  0.00000000000E+00 0.  1.
        6    1    1    2  501    0 -0.13244216743E+03 -0.16326397666E+03 -0.47746002227E+02  0.27641406353E+03  0.17300000000E+03 0. -1.
       -6    1    1    2    0  503  0.13244216743E+03  0.16326397666E+03 -0.23304746164E+03  0.35837992852E+03  0.17300000000E+03 0.  1.

And here is my program which simply reads in the text file and puts it into an array (or more specifically, a vector of vectors):

vector <float> vec; //define vector for final table for histogram.
    string lines;
    vector<vector<float> > data; //define data "array" (vector of vectors)

    ifstream infile("final.txt"); //read in text file

    while (getline(infile, lines))
    {
        data.push_back(vector<float>());
        istringstream ss(lines);
        int value;
        while (ss >> value)
        {
            data.back().push_back(value); //enter data from text file into array
        }
    }

    for (int y = 0; y < data.size(); y++)
    {
        for (int x = 0; x < data[y].size(); x++)
       {
            cout<<data[y][x]<< " ";
        }
        cout << endl;
   }
//  Outputs the array to make sure it works.

Now, this code works beautifully for the first 6 columns of the text file (these columns are entirely integers), but then it completely ignores every column 6 and higher (these are the columns containing scientific notation numbers).

I have tried redefining the vectors as both types double and float, but it still does the same thing. How can I get C++ to recognize scientific notation?

Thanks in advance!

1

There are 1 answers

1
Carlton On BEST ANSWER

Change int value; to double value; and also change your vector to double instead of int.

Better yet, since you have three declarations that must all be synchronized to the correct type, make an alias to that type like this: using DATA_TYPE = double; then declare your vectors and such like this: vector<vector<DATA_TYPE> > data;, DATA_TYPE value;, etc. That way if you change the type of the data for whatever reason, all your vector and variable declarations will update automatically, thus avoiding these kinds of bugs.