C++ 读取/写入C+中的文件+;
尝试读/写时,我的程序正确写入文件,但读取不正确 其中,l、w、n是C++ 读取/写入C+中的文件+;,c++,file,io,C++,File,Io,尝试读/写时,我的程序正确写入文件,但读取不正确 其中,l、w、n是int,而转置的是bool void Matrix::operator >> (ifstream & f) { f >> l; //length (int) f >> w; //width (int) f >> n; //size (int) f >> transposed; //(bool) theMatrix = v
int
,而转置的是bool
void Matrix::operator >> (ifstream & f)
{
f >> l; //length (int)
f >> w; //width (int)
f >> n; //size (int)
f >> transposed; //(bool)
theMatrix = vector<double>(0);
double v;
for (int i = 0; i < n; ++i) {
f >> v;
cout << " pushing back " << v << endl;
theMatrix.push_back(v);
}
}
void Matrix::operator<<(ostream & o)
{
o << l;
o << w;
o << n;
o << transposed;
//theMatrix is a vector<double>
for (double v : theMatrix) {
o << v;
}
}
void矩阵::运算符>>(ifstream&f)
{
f>>l;//长度(int)
f>>w;//宽度(int)
f>>n;//大小(int)
f>>转置;//(布尔)
矩阵=向量(0);
双v;
对于(int i=0;i>v;
您需要在打印的值之间留空格,以便在读回时知道每个值的结束位置。在每个值之间留一个空格。为类型T
定义输出运算符的正确方法是在std::ostream&operator前面加上签名std::ostream&operator。通常的方法是重载freestanding运算符函数std::ostream&operator(std::istream,Matrix&)
不用于二进制I/O,它们读取和写入格式化数据。写入时需要在每个值之间加空格,以便输入函数知道每个数字的结尾。@Jjoseph aboutread()
和write()
函数关于二进制文件。否则,请始终在输出中放置一个分隔的空格。@Jjosepho
std::ostream& operator<<(std::ostream o, const Matrix& m)
{
o << m.l << ' ' << m.w << ' ' << m.n << ' ' << m.transposed << ' ';
//theMatrix is a vector<double>
for (double v : m.theMatrix) {
o << v << ' ';
}
}