0

下面是我写的一段代码。我没有包含我的函数中的所有代码,因为我的工作计算机上没有它。我需要循环大约 10 行数据,收集信息,然后执行计算(calcdata)并输出到输出文本文件(senddata)。我的函数似乎工作得很好,但它们没有读过我文本文档的第一行。我能够读取第一行,计算第一行,然后输出第一行。

    /*    
    My input file is:

        10  0   S   Y   100
        5   7   S   N   50
        20  4   D   Y   9
        11  2   S   Y   6
        5   1   S   N   120
        31  5   S   N   500
        15  3   D   N   40
        18  4   S   N   50
        12  0   S   N   40
        26  7   D   Y   200

    */

    void getdata (int & adultget, int & childget, char & mealtypeget, char & weekendget, int & depositget, bool & error)

    ifstream infile;
    ofstream outfile;

    int main ()
        {
                infile.open("C:\\input.txt");
                outfile.open("C:\\output.txt");
                while (infile)
                        {
                            getdata(adult, child, mealtype, weekend, deposit, error);
                            calcdata(adult, child, mealtype, weekend, deposit, adultcost, childcost, totalfood, surcharge, tax, tip, totalparty, discount, totaldue);
                            senddata(adultcost, childcost, mealtype, weekend, deposit);
                        }
         infile.close();
         outfile.close();
         return 0;
         }

    void getdata (int & adultget, int & childget, char & mealtypeget, char & weekendget, int & depositget, bool & error)
        {
                infile >> adultget >> childget >> mealtypeget >> weekendget >> depositget;
                .
                .
                .
        }

我的输入文件有大约 10 行数据,混合了 int 和 char。我的函数只读取文件的第一行。有什么帮助吗?

4

3 回答 3

0

您应该在正确的位置检查流。更改getdata返回 a bool

bool getdata (...)
{
   bool ok = infile >> adultget >> ...;

   ...

   return ok;
}

循环应该是这样的:

while (getdata(adult, child, ... ))
{

    calcdata(adult, child, ...);
    senddata(adultcost, childcost, ...);
}
于 2013-11-14T18:51:53.873 回答
0

我只能猜测问题是在您读取数据时发生了一些错误,例如文件中的数据格式可能不正确。

于 2013-11-14T18:49:15.200 回答
0

您的 getdata() 方法会更改成人、儿童等的本地副本...如果您希望 main 中的值发生变化,则需要通过引用将参数传递给它。

即 void getdata(int & Adultget, int & childget .. 等等

于 2013-11-14T18:44:52.977 回答