[英]Reading / Writing a File in C++
尝试读/写我的程序正确写入文件但读取不正确。
其中 l, w, n 是ints
, transposed
是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;
}
}
我假设问题是由于读operator >>
不知道要读取多少字节,而写operator <<
没有写入一定数量的位/字节。 有没有办法澄清要读/写的字节数,以便我的程序相应地写入?
我对 C++ 并不陌生,但我对它的 IO 结构并不陌生。 我被 Java 的序列化方法宠坏了。
您需要在打印的值之间留有空格,以便在您读回它时知道每个值的结束位置。 在它们之间放置一个空格。 为类型T
定义输出运算符的正确方法是使用签名std::ostream& operator<<(std::ostream, const T&)
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 << ' ';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.