【发布时间】:2013-06-15 11:21:34
【问题描述】:
我想从一个文件中加载一个多维数组,我有这个代码:
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;
}
【问题讨论】:
-
该文件只是一个简单的矩阵,其中总是列 = 行。
-
@DavidJashi:不,它没有。它只读取下一个整数。
-
@user2252786:您考虑过
fin >> temp失败的可能性吗?您的代码应处理并报告此问题。 -
所以这应该可行...?我通过几个测试发布了整个功能,也许这会给你一些提示。
-
为什么那个循环首先读取整个文件?
标签: c++