2017-02-04 62 views
-2

在尝试读取/写入我的程序时,正确地写入文件,但未正确读取,正在使用C++读取/写入文件

其中l,w,n是intstransposedbool

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的序列化方法。

+0

就在'运营商<<'产生的输出,它创建了一个完全空'VECTOR',并试图打印的内容这个空的向量。毫不奇怪,没有输出结果。你究竟在哪里预料到输出是来自那个空载体? –

+0

通常的方法是重载独立运算符函数'std :: ostream&operator <<(std :: ostream,const Matrix&)'和'std :: istream&operator >>(std :: istream,Matrix&)'。 –

+1

'<<' and '>>'不用于二进制I/O,它们读取和写入格式化数据。每次写入时都需要在每个值之间放置空格,以便输入函数可以知道每个数字的结束位置。 – Barmar

回答

1

您需要在打印的值之间留出空格,以便在读取它时知道每个值的结束位置。在它们之间放一个空格。和定义输出操作的类型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 << ' '; 
    } 
}