Question

I am trying to write something on the file. But its just not writing as it must suppose to.

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();
}

And it writes in the file is like so:

99
Mak
3.780703e-42

What am I doing wrong?

Was it helpful?

Solution 2

You are using the incorrect variable names and using variables before they've been read and initialized.

This line writefile << name << endl; needs to follow cin >> name; In your code, it proceeds it and that means name doesn't contain anything or maybe junk data.

I think these lines

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

Should be:

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

OTHER TIPS

At the first writefile<<name<<endl, name field is undefined. May be would you like to write accno instead of name ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top