我想从一个文件中加载一个多维数组,我有这段代码:
std::vector<std::vector<int>> matrix;
for (int r = 0; r < cols; r++)
{
std::vector<int> row;
for ( int c = 0 ; c < cols ; c++ )
{
int temp;
if ( fin >> temp )
{
std::cout << temp;
row.push_back(temp);
}
}
matrix.push_back(row);
}
Cols 变量很好,如果我有 3x3 数组,嵌套循环被调用 9 次,所以这按预期工作......但是文件似乎无法读取单个整数(fin >> temp
). Fin 是文件处理程序。怎么了?
文件内容:
0 1 1
0 0 1
1 1 1
完整代码:
std::vector<std::vector<int>> foo()
{
std::string filename;
std::cout << "Filename: ";
std::cin >> filename;
std::vector<std::vector<int> > matrix;
std::ifstream fin(filename);
if(!fin) {
std::cout << "Error";
exit(EXIT_FAILURE);
}
std::string line;
int cols = 0;
if(fin.is_open()){
while(!fin.eof()){
std::getline(fin,line);
cols++;
}
}
for (int r = 0; r < cols; r++)
{
std::vector<int> row;
for ( int c = 0 ; c < cols ; c++ )
{
int temp;
if ( fin >> temp )
{
std::cout << temp; // displays nothing
row.push_back(temp);
}
std::cout << temp; // displays some crap like -84343141
}
matrix.push_back(row);
}
std::cin >> filename; // to stop execution and see the results
return matrix;
}
最佳答案
您正在对文件进行第一次遍历以确定大小,但您将需要在第一次读取文件后重新打开该文件。否则,文件中没有剩余数据可供读取。
关于c++ - 从文件加载多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17123084/