我在c ++中有银行系统项目。我想提取金额但是当我提取金额时我不能在特定位置更新新的金额

时间:2017-11-02 09:42:48

标签: c++ file-handling

我想在帐户xyz中提取金额但是当我提取金额时我无法在特定位置(写入1200)的文件中更新新金额我该怎么办?

这是我的退出功能。

void withdraw()
{
    ofstream f2("bank",ios::out  | ios :: app);
    ifstream f1("bank",ios::in |  ios :: app);

    f1.seekg(0);
    long long a_num;
    long double w_amount;

    cout << "Enter Account Number :" << endl;
    cin  >> a_num;
    Bank ac;

    while (f1 >> acc_num >> name >> acc_type >> amount){

        if(acc_num == a_num){

            int g = f1.tellg();
            cout << "Get" << g << endl;
            int p=g;
            acc_num=0;
            f2.seekp(p,ios::beg);
            cout << "Name         :" << name << endl;
            cout << "Account type :" << acc_type << endl;
            cout << "balance      :" << amount << endl;

            cout << "Enter withdraw amount : " << endl;
            cin  >> w_amount;
            amount = amount - w_amount;
            cout << "Balance :" << amount << endl;

            f2.seekp(p,ios::beg);

            f2 << amount << endl;
        }

    }
}

以下是文件looks like

的内容
bank.txt
12345678901234   xyz    savings    1200
12345678901235   pyr    current    1600

1 个答案:

答案 0 :(得分:0)

问题非常基本,您的文件名是 bank.txt ,但您传递的是 ifstream ofstream 对象 ctor 只是银行,这不会起作用,因为开放操作可能会打开其他文件,

ofstream f2("bank",ios::out | ios :: app); 
ifstream f1("bank",ios::in | ios :: app); 

其次,你不能同时打开同一个文件,你可以使用 fstream 对象

fstream fp("bank.txt",ios::in | ios::out | ios::app);

解决你的问题,使用fp.write ()函数写入文件,其第一个参数是指向字符的指针,第二个是写入文件的字符数,因此可以相应地设置第二个参数

可能是这样的:

char text [5] = "good";
 // do the seekp operation.
fp.write (text,5);

有关更多知识,请参阅此http://www.cplusplus.com/reference/ostream/ostream/write/