【问题标题】:c++ - having trouble with writing in the file (ofstream)c++ - 写入文件时遇到问题(ofstream)
【发布时间】:2014-04-23 20:00:14
【问题描述】:

我正在尝试在文件上写一些东西。但它只是没有像它必须假设的那样写作。

void main()
{
    int accno;
    char name[20];
    float deposit;

    clrscr();

    ofstream writefile("icici.txt");

    cout<<"enter your saving bank account number";
    cin >> accno;

    writefile << name << endl;

    cout<<"\n\nYour good name:";
    cin >> name;
    writefile << name << endl;

    cout<<"\n\nKey in recent deposit in Rs:";
    cin >> accno;

    writefile << deposit << endl;

    writefile.close();

    cout << "\n\nFile is created successfully...\n\n" << endl;
    ifstream readfile("icici.txt");
    readfile >> accno;
    readfile >> name;
    readfile >> deposit;
    cout<<"\nContent of file is icici.txt is read as follows:\n";
    cout<<"\nSaving bank account number:"<<accno<<endl;
    cout<<"\nCustomer name smt/shri:"<<name<<endl;
    cout<<"\nDeposit amount in Rs:"<<deposit<<endl;
    getch();
}

它在文件中写的是这样的:

99
Mak
3.780703e-42

我做错了什么?

【问题讨论】:

  • 你想做什么?预期的结果是什么?
  • 打开编译器警告并仔细查看提示输入存款金额后的行。
  • 第 14 行,writefile &lt;&lt; name &lt;&lt; endl; 名称未初始化。
  • cin &gt;&gt; accno; 出现 2 次。你想要cin &gt;&gt; deposit 第二次。
  • 天啊,我真的很抱歉我的坏! :D

标签: c++ fstream ofstream


【解决方案1】:

在第一个writefile&lt;&lt;name&lt;&lt;endlname 字段未定义。您可能想写accno 而不是name 吗?

【讨论】:

    【解决方案2】:

    您使用了不正确的变量名称,并且在读取和初始化变量之前使用了这些变量。

    writefile &lt;&lt; name &lt;&lt; endl; 这一行需要跟随 cin &gt;&gt; name; 在您的代码中,它会继续它,这意味着 name 不包含任何内容或可能是垃圾数据。

    我认为这些台词

    cout<<"\n\nKey in recent deposit in Rs:";
    cin >> accno;
    

    应该是:

    cout<<"\n\nKey in recent deposit in Rs:";
    cin >> deposit;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      相关资源
      最近更新 更多