while(infile)循环只从我的文本文件中读取第一行

时间:2013-11-14 18:40:14

标签: c++

下面是我写的一段代码。我没有包含我的函数中的所有代码,因为我目前没有在我的工作计算机上使用它。我需要遍历大约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。我的功能只是读取文件的第一行。有什么帮助吗?

3 个答案:

答案 0 :(得分:0)

你的getdata()方法改变了成人,孩子等的本地副本......如果你希望在main中返回的值能够改变,你需要通过引用将参数传递给它。

即。 void getdata(int& adultget,int& childget ..等等

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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

   ...

   return ok;
}

并且循环应该像:

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

    calcdata(adult, child, ...);
    senddata(adultcost, childcost, ...);
}
相关问题