c ++ - 在文件中写入有问题(ofstream)

时间:2014-04-23 20:00:15

标签: c++ fstream ofstream

我正在尝试在文件上写点东西。但它只是不写,因为它必须假设。

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

我做错了什么?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

此行writefile << name << endl;需要关注cin >> name;在您的代码中,它继续进行,这意味着名称不包含任何内容或垃圾数据。

我认为这些行

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

应该是:

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