想试着写一个做矩阵运算的代码,然后发现一直都无法使用getline()
从文件中读取矩阵。但是我在别的代码中却可以使用getline()
,下面是代码。
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <vector>
using namespace std;
typedef vector<vector<int>> douvec;
//产生一个含有矩阵的文件,这里能够正常的产生矩阵文件
void create_file (fstream &file) {
int rank;
//提示输入产生的矩阵的维度
cout << "input the rank: ";
cin >> rank;
//随机生成矩阵的数值
srand(time(0));
for (int r = 0; r < rank; r++){
for (int c = 0; c < rank; c++)
file << rand()%2 << " ";
file << '\n';
}
}
//讲文件中的矩阵读入一个二维vector中
auto create_matrix (fstream &file) -> vector<vector<int>> {
char num;
string line;
douvec matrix;
//这里的getline一直都读取不了文件中的任何的数据
while (getline(file, line)){
stringstream record(line);
vector<int> temp;
if (line == "")
break;
while (record >> num){
int number = (int)num;
temp.push_back(number);
}
matrix.push_back(temp);
}
return matrix;
}
int main(){
fstream file("file.txt", ofstream::app);
douvec matrix;
create_file(file);
//这里输出的matrix.size()一直都是0
cout << "matrix size is " << matrix.size() << endl;
matrix = create_matrix(file);
for (int row = 0; row < matrix.size(); ++row){
for (int col = 0; col < matrix[row].size(); ++col)
cout << matrix[row][col] << " ";
cout << endl;
}
return 0;
}
The reason why you cannot read the file content using getline is because of improper use
two problems
If you want to read and write an fstream at the same time, you should add the corresponding mode
fstream file("file.txt", ofstream::in | ofstream::app);
c++ fstream is actually just a repackage of C FILE I/O.
See c++11 N3337 27.9.1.1
Watch c11 WG14 N1570 7.21.5.3
So just add
matrix = create_matrix(file);
or other repositioning in front of
file.seekg(0, std::ios_base::beg);
.