我已经写了一个函数,用于从文件读取未知数量的数据(当在一列中)到一个向量。函数从文件读入向量C++
#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是增加一个额外的时间之后,从该文件中的数据已经被复制到载体。有没有比我写的if语句更优雅的解决这个问题的方法?
编辑:显然,我不会上传数据文件。代码完美编译我只是在if语句中寻找改进(如果存在的话)。
使用函数getline()来代替。 –
@Matt你在说什么?代码在VS15中编译得很好 – nikjohn
使用x.push_back()而不是x.at(linecount),将N direct传递给ReadFromFile,构造v但留空,并保留N个元素。 –