Search code examples
c++arraystextfstream

Input Numbers from txt file to array


I'm pretty sure that this is a common question, but I can't find an example similar to mine, so.. I have a text file called input.txt that has: 0.0001234 1.0005434 0.0005678 1.0023423 0.00063452 1.0001546 0.00074321 1.00017654 in it. Now I want to write a program to read that into an array, and then quickly check that it worked. So far, I've got:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{
    double PA[8];
    int n;
    ifstream myfile ("input.txt");
    if (myfile.is_open())
    {
        while (! myfile.eof() )
        {
            getline (myfile,line);
            cout << PA[line]<< endl;

        }
        myfile.close();
    }
    else cout << "Unable to open file";
    for (n=0; n<8; n++) // to print the array, to check my work
    {
         cout << " {" << PA[n] << "} ";
}

    system("PAUSE");
    return 0;
}

My problem so far is that I keep getting the error: line was not declared. And I want to use the array later with floats to calculate new data. I think I'm doing it wrong for that.. Any help? Thanks!


Solution

  • declare line variable

    int n, line = 0;
    std::string value;
    

    proper load data:

    getline (myfile,value);
    PA[line] = atof(value.c_str());
    cout << PA[line]<< endl;
    line++;