【问题标题】:C++ file stream and vectorsC++ 文件流和向量
【发布时间】: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;
}

这是我目前的代码

【问题讨论】:

标签: c++ file loops vector stream


【解决方案1】:

用这样的文件在本地尝试:

12 34 42 53
32 45 46 47
31 32 33 34

并且必须更改读数(您的代码中没有任何行解析)。工作示例如下:

//copy specified data into vector
string line;
int i, j, offset, int_val;
size_t tmp;
i = 0;
while( file.good() && (i<row) ){
  getline( file, line );
  //create one line in data
  data.push_back( vector<int>(0) );
  offset = 0;
  j = 0;
  //parse one line
  while( 1 ){
    try{
      int_val = stoi( line.substr(offset), &tmp );
    }catch( const exception& e){
      //ending loop when no more numbers available
      ++i;
      break;
    }
    //exiting loop when reqiuered limit reached
    if( j >= col ){
      ++i;
      break;
    }
    //save to vector
    data[i].push_back( int_val );
    offset += tmp;
    ++j;
  }
}
file.close();     //don't forget to close the file

打印输出好像没问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-05
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 2011-03-01
    • 2020-12-17
    相关资源
    最近更新 更多