函数从文件读入向量c++

Function reading from a file into vector C++

本文关键字:c++ 向量 从文件读 函数      更新时间:2023-10-16

我写了一个函数,将未知数量的数据(当在列中)从文件读取到向量。

#include <iostream>
#include <vector>
#include <fstream> // file writing
#include <cassert>

void ReadFromFile(std::vector<double> &x, const std::string &file_name)
{
    std::ifstream read_file(file_name);
    assert(read_file.is_open());
    size_t lineCount = 0;
    while (!read_file.eof())
    {
        double temp;
        read_file >> temp;
        x.at(lineCount) = temp;
        if (lineCount == x.size() - 1) { break; } // fixes the out of range exception
        lineCount++;
    }
    read_file.close();
}
int main()
{
    size_t Nx = 7;
    size_t Ny = 7;
    size_t Nz = 7;
    size_t N = Nx*Ny*Nz;
    // Initial Arrays 
    std::vector <double> rx(N);
    std::string Loadrx = "Loadrx.txt";
    ReadFromFile(rx, Loadrx);
}

但是lineCount会在文件中的数据被复制到vector之后再增加一次。有没有比我写的if语句更优雅的方法来解决这个问题?

我写了一个函数,读取一个未知的数量的数据(当在一个列中)从一个文件到一个向量。

从"列"(或其他规则格式化的)文件中读取未知数量数据的最优雅(我认为也是最惯用的)方法之一是使用istream迭代器:

void ReadFromFile(std::vector<double> &x, const std::string &file_name)
{
    std::ifstream read_file(file_name);
    assert(read_file.is_open());
    std::copy(std::istream_iterator<double>(read_file), std::istream_iterator<double>(),
        std::back_inserter(x));
    read_file.close();
}

用法:

int main()
{
    // Note the default constructor - we are constructing an initially empty vector.
    std::vector<double> rx;
    ReadFromFile(rx, "Loadrx.txt");
}

如果你想写一个"安全"的版本,读取的元素数量有限,使用copy_if:

void ReadFromFile(std::vector<double> &x, const std::string &file_name, unsigned int max_read)
{
    std::ifstream read_file(file_name);
    assert(read_file.is_open());
    unsigned int cur = 0;
    std::copy_if(std::istream_iterator<double>(read_file), std::istream_iterator<double>(),
    std::back_inserter(x), [&](const double&) {
        return (cur++ < max_read);
    });
    read_file.close();
}

用法明显:

ReadFromFile(rx, Loadrx, max_numbers);

尝试:

void ReadFromFile(const size_t N, 
                  std::vector<double> &x, 
                  const std::string &file_name)
{
    std::ifstream read_file(file_name);
    assert(read_file.is_open());
    while (true)
    {
        double temp;
        read_file >> temp;  // read something
        if(read_file.eof()) break; // exit when eof
        x.push_back(temp);    
        if (N == x.size()) break;  // exit when N elements
    }
    read_file.close();
}
int main()
{
    size_t N = 10;
    std::vector<double> v;
    v.reserve(N);
    ReadFromFile(v,"Data.txt");
}