在尝试读取/写入我的程序时,正确地写入文件,但未正确读取,正在使用C++读取/写入文件
问题描述:
。在尝试读取/写入我的程序时,正确地写入文件,但未正确读取,正在使用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 << ' ';
}
}
就在'运营商
通常的方法是重载独立运算符函数'std :: ostream&operator >(std :: istream,Matrix&)'。 –
'>'不用于二进制I/O,它们读取和写入格式化数据。每次写入时都需要在每个值之间放置空格,以便输入函数可以知道每个数字的结束位置。 – Barmar