C++ 从文件加载多维数组
我想从文件中加载多维数组,我有以下代码:C++ 从文件加载多维数组,c++,C++,我想从文件中加载多维数组,我有以下代码: 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::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);
}
整个代码:
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;
}
std::vector foo()
{
std::字符串文件名;
std::cout>filename;
向量矩阵;
std::ifstream-fin(文件名);
如果(!fin){
标准:温度>温度)
{
std::cout filename;//停止执行并查看结果
收益矩阵;
}
您正在对文件进行第一次遍历以确定大小,但在第一次读取文件后需要重新打开该文件。否则,文件中没有要读取的数据。请尝试添加
fin.seekg (0, is.beg);
在循环之前
因为在
std::string line;
int cols = 0;
if(fin.is_open()){
while(!fin.eof()){
std::getline(fin,line);
cols++;
}
}
您将在文件中的eof
和
if ( fin >> temp )
将始终返回false。这就是为什么需要将位置设置为文件的开头
您还可以替换
while(!fin.eof()){
std::getline(fin,line);
cols++;
}
更容易
while(std::getline(fin,line)) cols++;
首先读取文件,计算行数和列数,然后关闭文件。
然后再次读取文件,现在循环到计算出的行和列文件只是一个简单的矩阵,其中总是列=行。@DavidJashi:不,它不会。它只读取下一个整数。@user2252786:您是否考虑过
fin>>temp
失败的可能性?您的代码应该处理并报告这个问题。所以这应该是可行的。。。?我通过几个测试发布了整个函数,也许这会给你更多提示。为什么那里的循环首先读取整个文件?
while(std::getline(fin,line)) cols++;