【问题标题】:Reading number from txt file, add some it with some number & then rewrite it to a different file in c++从 txt 文件中读取数字,添加一些数字,然后将其重写到 c++ 中的不同文件
【发布时间】:2014-01-10 15:51:02
【问题描述】:

我正在制作一个用于练习的计费系统,并且有一个选项可以显示以前的销售。(如果存在,则从文件中读取以前的销售,将其与以前的销售一起添加到新的销售中并写在 txt 文件中)。我已经尝试过了但有一些逻辑错误。请尽快帮助我。

#include<iostream>
#include<fstream>
using namespace std;
int main ()
{
    int choice,sale,pre_sale,t_sale;
    ifstream saleFilein;
    ofstream saleFileout;
    do
    {
        cout<<"1 : Enter new sale\n"
          <<"2 : View previous sale\n"
          <<"3 : Exit\n";
        cin>>choice;

        if(choice==1)
        {
            system("cls");
            cout<<"Enter the sale: ";
            cin>>sale;
            saleFileout.open("testsale.txt");

            saleFilein.open("testsale.txt");
            saleFilein>>pre_sale;
            saleFilein.close();
            sale+=pre_sale;
            saleFileout<<sale;
            saleFileout.close();
        }
        else if(choice==2)
        {
            saleFilein.open("testsale.txt");
            saleFilein>>t_sale;
            saleFilein.close();
            cout<<"THE PREVIOUS SALE IS"<<t_sale;
        }
    }
    while(choice<3);
}

【问题讨论】:

  • 销售未正确显示。添加新销售时。
  • 可能有一些缩进?也给我们展示一个输入和输出的例子。

标签: c++ if-statement file-handling do-while


【解决方案1】:

以下main 将按预期工作:

int main()
{
    int choice,sale,pre_sale,t_sale;
    //ifstream saleFilein;
    //ofstream saleFileout;
    do
    {
        cout<<"1 : Enter new sale\n"
          <<"2 : View previous sale\n"
          <<"3 : Exit\n";
        cin>>choice;

        if(choice==1)
        {
            system("cls");
            cout<<"Enter the sale: ";
            cin>>sale;

            ifstream saleFilein("testsale.txt");
            assert(saleFilein);
            saleFilein>>pre_sale;
            if (!saleFilein)
                pre_sale = 0;
            saleFilein.close();

            ofstream saleFileout("testsale.txt");
            sale+=pre_sale;
            saleFileout<<sale;
            saleFileout.close();
        }
        else if(choice==2)
        {
            ifstream saleFilein("testsale.txt");
            saleFilein>>t_sale;

            if (saleFilein)
                cout<<"THE PREVIOUS SALE IS "<<t_sale<<endl;
            else
                cout<<"No previous sale"<<endl;

            saleFilein.close();
        }
    }
    while(choice<3);

    return 0;
}

当文件丢失时,您在不验证输入时遇到了一个小问题。但主要的似乎与流的奇怪的内部错误状态标志有关:在关闭流后它们似乎仍然存在并通过未来的打开操作保持活动状态。为了解决最后一个问题,我更喜欢简化代码并本地化流变量的使用。如果必须的话,我可以把代码改回来,但更多的是C++这样的方式。

【讨论】:

  • 对不起兄弟我看不懂:(.你能简单解释一下吗。
  • :)),我不知道你不明白什么。上面的代码应该适合你,是吗?
  • 它的工作感谢您帮助我。我正在询问 assert()
  • 你可以去掉'assert',它只是为了帮助调试。它不会改变程序流程。
  • 下面的逻辑是什么。
猜你喜欢
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-27
  • 1970-01-01
相关资源
最近更新 更多