为什么我的这段代码不能写入文件

Why won't this piece of my code write to file

本文关键字:不能 文件 代码 我的 段代码 为什么      更新时间:2023-10-16

我正在开发一个C++银行系统。我能够正确获取浮点数、newbal 值,当我尝试写入文件时,文件中没有数据。

else if (x == 2)
{
    cout << "You have selected option number 2. Deposit.n";
    cout << "Please enter you account ID: ";
    cin >> ID;
    file.open("C:\Users\Raggulddon\Desktop\C++ supplement\Cust_" + ID + ".dat", ios:: in | ios::out | ios::binary);
    if (!file)
    {
        cout << "Sorry the requested account could not be located.n";
    }
    else
    {
        file >> firstname >> lastname;
        cout << endl << firstname << " " << lastname << endl;
        cout << "-----------------------------------n";
        string line;
        while (getline(file, line))
        {
            // stringstream the getline for line string in file
            istringstream iss(line);
            if (iss >> date >> amount)
            {
                cout << date << "tt$" << showpoint << fixed << setprecision(2) << amount << endl;
                famount += amount;
            }
        }
        cout << "Your balance is $" << famount << endl;
        cout << "How much would you like to deposit today: $";
        cin >> amountinput;
        float newbal = 0;
        newbal = (famount += amountinput);

        cout << "nYour new balance is: $" << newbal << ".n";
        file << date << "tt" << newbal; //***This should be writing to file
        but it doesn 't.
            
file.close();

文本文件如下所示:

托尼·加迪斯

12-05-24 100

12-05-30 300

12-01-07 -300

控制台输出如下所示

托尼·加迪斯

12-05-24 100

12-05-30 300

12-01-07 -300

您的余额为:#1

您想存入多少:#2

您的新余额是: #1 + #2

写入文件

关闭文件。

退出主循环::::

如何使其写入文件并保存,以及为什么会发生这种情况。

考虑到如何使用istringstream输入,我也尝试使用ostringstream来执行此操作。但它也没有用:

float newbal=0;
newbal = (famount += amountinput);
ostringstream oss(newbal);
oss << date << "tt" << newbal;

我正在尝试自学C++因此任何相关信息将不胜感激。

如果要

编写文本文件,则在打开文件时不应使用"ios::binary"。