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

旧巷老猫 提交于 2021-01-28 21:29:03

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/65645056/how-to-read-n-values-from-txt-file-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!