[英]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.