提取和存储数据到 ostream

问题描述

是否可以像这样将数据存储到 ostream

void write(std::ostream& os){
  int x,y = 0; bool b = true;
  os<<x<<" "<<y<<" "<<b<<std::endl;
}

然后像这样从中提取数据

void read(std::istream& is){
  unsigned int x,y,b;
  is>>x>>y>>b; // I want to take x,b and make store them in a object but it is not important I want to kNow if I can extract @R_161_4045@ion from istream like this and use x,b
}

我试着做一个简单的程序来试试

#include <iostream>
#include <fstream>
#include <string>

int main(int argc,char const *argv[]) {
  std::fstream file(argv[1]);
  if (!file.is_open()){
    std::cerr<<"erreur"<<std::endl;
    return 1;
  }
  bool v = false;
  size_t x = 1;
  size_t y = 2;
  for(size_t i=0;i<4;i++) {
    file<<v<<" "<<x<<" "<<y<<std::endl;
  }
  for (size_t j = 0; j < 4; j++) {
    bool b; size_t a; size_t c;
    file>>b>>a>>c;
    std::cout<<b<<a<<c<<std::endl;
  }
  return 0;
}

但我的输出是这样的:

026422044
026422044
026422044
026422044

解决方法

关闭并重新打开文件后,我的问题解决了。

#include <iostream>
#include <fstream>
#include <string>

int main(int argc,char const *argv[]) {
  std::ofstream file(argv[1]);
  if (!file.is_open()){
    std::cerr<<"erreur"<<std::endl;
    return 1;
  }
  bool v = false;
  size_t x = 1;
  size_t y = 2;
  for(size_t i=0;i<4;i++) {
    file<<v<<" "<<x<<" "<<y<<std::endl;
  }
  file.close();
  std::ifstream file1(argv[1]);
  if (!file1.is_open()){
    std::cerr<<"erreur"<<std::endl;
    return 1;
  }
  for (size_t j = 0; j < 4; j++) {
    size_t b; size_t a; size_t c;
    file1>>b>>a>>c;
    std::cout<<b<<a<<c<<std::endl;
  }
  return 0;
}