2

我正在编写一个程序,该程序必须将文件中的数据导入到各种容器中。我让它正确导入所有内容,但在应该是 eof 之后它会继续阅读。我有一种感觉,我没有正确地告诉循环何时结束,但下面的代码供大家查看。

bool InitLoad(vector<string>&num, vector<string>&name, vector<double>&price, vector<char>&tax)
{
    ifstream invFile;
    int intTemp;
    string strTemp;
    double dubTemp;
    char chTemp;
    string fileLoc = "C:/Users/owner/Documents/Visual Studio 2010/Projects/CISS 350/Week 1 Grocery Register/Week 1 Grocery Register/Invent.dat";

    //Open Invent.dat file. Location below is the location used on creators computer. Other may need to modify file location
    invFile.open(fileLoc.c_str(), ios::in);

    //If Invent.dat file fails to open display error message and return false
    if(invFile.fail())
    {
        cout << "Could not open inventory file" << endl;
        return false;
    }
    if(invFile)
    {
        //Read first line of the file
        getline(invFile, strTemp, ' ');
        while(invFile)  //while invFile contains data display import the list
        {
            cout << strTemp << " ";
            num.push_back(strTemp);

            getline(invFile, strTemp, ' ');
            cout << strTemp << " ";
            name.push_back(strTemp);

            getline(invFile, strTemp, ' ');
            dubTemp = atof(strTemp.c_str());
            cout << dubTemp << " ";
            price.push_back(dubTemp);

            invFile.get(chTemp);
            cout << chTemp;
            tax.push_back(chTemp);

            getline(invFile, strTemp, ' ');
        }
    }

    invFile.close();

    cout << endl;
    //Verify Proper input...REMOVE WHEN COMPLETE
    cout << "Verifying input data correct..." << endl;
    int vecSize = num.size();
    cout << vecSize << endl;
    for(int i = 0; i < vecSize; i++)
    {
        cout << num[i] << " " << name[i] << " " << price[i] << " " << tax[i] << endl;
    }

}
4

2 回答 2

4

您的支票不检查 eof 标志 http://www.cplusplus.com/reference/ios/ios/operator_bool/

invFile.eof()改为使用

并且在阅读过去的 EOF也会设置 eof 标志

PS:天啊!!不使用atof,只做invFile << dubTemp

于 2013-03-26T16:32:34.497 回答
0

由于您的数据是空格分隔的,您可以在每个字符串上使用格式化输入而不是 getline()。与此类似的东西。

 string lineTemp;
 while(getline(invFile, lineTemp))  //while invFile contains data display import the list
    {
        string strTemp1, strTemp1, dubTemp, chTemp;
        istringstream lstr(lineTemp);

        if(lstr >> strTemp1 >> strTemp2 >> dubTemp >> chTemp) {

            num.push_back(strTemp1);
            name.push_back(strTemp2);
            price.push_back(dubTemp);
            tax.push_back(chTemp);


            cout << strTemp1 << " "
                 << strTemp2 << " "
                 << dubTemp << " "
                 << chTemp << endl;
         }

         else {
             // Something is wrong with the line format.
         }


    }

这将以格式化的方式和正确的类型读取数据。另外,您不必担心空行或行中的多余字符。

于 2013-03-26T16:53:34.800 回答