无法使用 fstream 将值存储在文本文件中

not able to store value in text file using fstream

本文关键字:存储 文本 文件 fstream      更新时间:2023-10-16

我是C ++编程的新手,我无法存储在文本文件中。这是一个非常简单的程序。我之前使用与我得到结果相同的方法存储值。

#include<iostream>
#include<fstream>
using namespace std;
int main() {
  ofstream fout("one.txt",ios::in);
  int val1, rel1;
  char val2[20], rel2[20];
  cout<<" n enter the integer value";
  cin>>val1;
  cout<<" n enter the string value ";
  cin>>val2;
  fout.close();
  ifstream fin("one.txt");
  fin>>rel1;
  fin>>rel2;
  cout<<"the integer value .n"<<rel1;
  cout<<"the string value .n"<<rel2;
  fin.close();
  if (fout==NULL) {
    cout<<"the file is empty";
  }
  return 0;
}

输入100名字 荒谬的输出是整数值为 32760字符串值为 00Dv0

> 这里有许多假设似乎需要澄清。

  • 如果要写入文件,则需要使用 fout <<rel1;
  • 您(通常)不能像在 if(fout == NULL) 中那样将对象与 NULL 进行比较。这适用于 C# 和 Java,因为在这些语言中,所有对象实际上都是引用,C++中您可以指定何时需要对象以及何时需要引用。
  • 您指定要使用 fout 从文件中读取而不是写入文件,即"ios::in"。

等待一些测试完成有点无聊,所以我写了我如何编写该程序:

#include<iostream>
#include <string>
#include<fstream>
int main() {
  std::ofstream fout("one.txt",std::ios::out);
  int val1, rel1;
  std::string val2, rel2;
  std::cout <<"enter the integer value: ";
  std::cin >>val1;
  std::cout <<"enter the string value: ";
  std::cin >>val2;
  fout <<val1 <<" " <<val2;
  fout.close();
  std::ifstream fin("one.txt", std::ios::in);
  if(!fin.good()) {
    std::cout <<"Failed to open filen";
    return 1;
  }
  fin >>rel1;
  fin >>rel2;
  std::cout <<"the integer value: " <<rel1 <<"n";
  std::cout <<"the string value: " <<rel2 <<"n";
  fin.close();
  return 0;
}