Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 读取/写入C+中的文件+;_C++_File_Io - Fatal编程技术网

C++ 读取/写入C+中的文件+;

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

尝试读/写时,我的程序正确写入文件,但读取不正确

其中,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 = 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 about
read()
write()
函数关于二进制文件。否则,请始终在输出中放置一个分隔的空格。@Jjoseph
o
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 << ' ';
    }
}