如何使用C ++从txt文件读取n个值 [英] How to read n values from txt file using C++

查看:66
本文介绍了如何使用C ++从txt文件读取n个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下c ++代码,可用来从.txt文件中读取值

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

请帮助我改善代码,以便我不仅可以读取.txt中的14个值,还可以读取n个值

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";
}

.txt文件看起来像

the .txt file looks like

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

推荐答案

vec.push_back(value);

这里,值已经添加到 vec 中,您无需再次将它们添加到 a 中.您只需输入 vec [n] 即可访问这些值.例如,

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.

这篇关于如何使用C ++从txt文件读取n个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆