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

时间:2014-03-05 12:30:07

标签: c++

我是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

1 个答案:

答案 0 :(得分:0)

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

  • 如果要写入文件,则需要使用fout&lt;&lt; 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 file\n";
    return 1;
  }

  fin >>rel1;
  fin >>rel2;

  std::cout <<"the integer value: " <<rel1 <<"\n";
  std::cout <<"the string value: " <<rel2 <<"\n";

  fin.close();

  return 0;
}