C ++从文件读取数字并存储在向量中 [英] C++ read numbers from file and store in vectors
问题描述
我无法撤消此方法,将基本上将可变大小的数字矩阵转储到文本文件中:
I am having trouble "undoing" this method, that dumps essentially a matrix of numbers of variable size into a text file:
void vectorToFile(char *name, vector<vector<double>>* a){
FILE* fp = fopen(name, "w");
for(int i=0;i<a->size();i++){
for(int j=0;j<a->at(i).size();j++){
fprintf(fp, "%f ", a->at(i).at(j));
}
fprintf(fp, "\n");
}
fclose(fp);
}
我在执行相反操作时遇到问题:
I am having trouble implementing the reverse:
vector<vector<double>> fileToVector(char *name){ ??? }
我保证文件中的数字形成一个矩形向量都是相等的,但我不知道如何计算每行的条目数和列数。
I am guaranteed that the numbers in the file form a "rectangle", i.e. the sizes of inner vectors are all equal, but I don't know how to figure out the number of entries per row, and the number of columns.
任何人都可以指向我的右边方向?到目前为止,我发现的每个例子实现的东西更容易,硬编码的大小,或第一行给出的大小(我不能负担不起)
Can anyone point me in the right direction? Every example I found so far implements something much easier, with hardcoded size, or sizes given in first row (which I cannot afford to do unfortunately)
推荐答案
我在C ++是新的,所以我不知道这是一个好的方法或不,但我会打开文件,读入输入行,每行解析我读它。下面是一些示例代码(未测试,未编译):
I'm new at C++ so I'm not sure if this is a good approach or not, but I would open the file, read in the input line by line, parsing each line as I read it. Here's some example code (untested, uncompiled):
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
std::vector<std::vector<double> > fileToVector(const char *name)
{
std::vector<std::vector<double> > result;
std::ifstream input (name);
std::string lineData;
while(getline(input, lineData))
{
double d;
std::vector<double> row;
std::stringstream lineStream(lineData);
while (lineStream >> d)
row.push_back(d);
result.push_back(row);
}
return result;
}
这篇关于C ++从文件读取数字并存储在向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!