Search code examples
c++stringstreamifstreamofstream

How to read n values from txt file using C++


I have the following c++ code by which I am reading values from .txt file

Could you please help me to improve the code such that I can read not only 14 values but n values from the .txt

//reading from text file
static std::vector<double> vec;
double a[14]; //values got read from txt file
int i = 0;
void readDATA()
{
    double value;
    std::ifstream myFile;
    myFile.open("filename.txt", std::ios::app);
    if (myFile.is_open())
    {
        std::cout << "File is open." << std::endl;
        while (myFile >> value)
        {
            vec.push_back(value);
            std::cout << "value is " << value << std::endl;
            a[i] = value;
            std::cout << "a" << i << "=" << a[i] << std::endl;
            i = i + 1;
        }
        myFile.close();
    }
    else
        std::cout << "Unable to open the file";
}

the .txt file looks like

0 0 40 45 15
0 1 40 -45 10
0 0 180 90 15

Solution

  • vec.push_back(value);

    Here, values are already added to vec, you don't need to add them to a again. You can just access those values by typing vec[n]. For example,

    std::cout<<vec[2]; //40
    std::cout<<vec[4]; //15
    

    And you can push back as many elements as you like to vectors, so you really don't need to declare another array or doubles.