【发布时间】:2018-03-23 09:49:30
【问题描述】:
我有一个 .dat 文件,其中包含 100 x 100 的整数,我正在尝试将 x 行和 x 列传输到一个新向量中,我设法将第一行包含所需的列,但一直在尝试要到下一行,直到到 x 行,请提供帮助。
在显示部分也有一些帮助,我不确定如何显示具有多个行和列的向量。尝试data.at(i).at(j) double for 循环但不成功
//variable
int row, col;
string fname;
ifstream file;
vector<vector<int>> data;
//input
cout << "Enter the number of rows in the map: "; cin >> row;
cout << "Enter the number of columns in the map: "; cin >> col;
cout << "Enter the file name to write: "; cin >> fname;
//open file
file.open(fname, ios::in); // map-input-100-100.dat map-input-480-480.dat
//copy specified data into vector
int count = 0, temp = 0;
string line;
while (count < row)
{
for (int i = 0; i < col; ++i)
{
file >> temp;
data[count].push_back(temp);
}
++count;
getline(file, line);
stringstream ss(line);
}
//output
for (int i = 0; i < data.size(); i++)
{
for (int j = 0; j < data[i].size(); j++) cout << data[i][j] << ' ';
cout << endl;
}
这是我目前的代码
【问题讨论】:
-
你听说过嵌套的for循环吗?这将有很大帮助...
-
关于文件读取循环。此答案中的选项 2 应该可以帮助您:stackoverflow.com/a/7868998/4581301
标签: c++ file loops vector stream