提取数据并将其存储到 ostream

Extracting and storing data to 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,y,b and make store them in a object but it is not important I want to know if I can extract information from istream like this and use x,y,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;
}