简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM