首页 > 解决方案 > C++: Using getline to input from a text file either skips the first line or messes up the rest

问题描述

I'm trying to read in from a specially formatted text file to search for specific names, numbers, etc. In this case I want to read the first number, then get the name, then move on to the next line. My problem seems to be with while loop condition for reading through the file line by line. Here is a sample of the txt file format:

5-Jon-4-Vegetable Pot Pie-398-22-31-Tue May 07 15:30:22 
8-Robb-9-Pesto Pasta Salad-143-27-22-Tue May 07 15:30:28 
1-Ned-4-Vegetable Pot Pie-398-22-31-Tue May 07 15:30:33 

I'll show you two solutions I've tried, one that skips the first line in the file and one that doesn't take in the very last line. I've tried the typical while(!iFile.eof()) as a last ditch effort but got nothing.

    transactionLog.clear();
    transactionLog.seekg(0, std::ios::beg);


    std::string currentName, line, tempString1, tempString2;
    int restNum, mealNum;
    bool nameFound = false;
    int mealCount[NUMMEALS];

    std::ifstream in("patronlog.txt");

    while(getline(in, line)) 
    {
        getline(in, tempString1, '-');
        getline(in, currentName, '-');

        if(currentName == targetName)
        {
            if(getline(in, tempString2, '-'))
            {
                mealNum = std::stoi(tempString2);
                mealCount[mealNum - 1] += 1;
                nameFound = true;
            }
        }

I believe I understand what's going in this one. The "getline(in, line)" is taking in the first line entirely, and since I'm not using it, it's essentially being skipped. At the very least, it's taking in the first number, followed by the name, and then doing the operations correctly. The following is the modification to the code that I thought would fix this.

    while(getline(in, tempString1, '-'))
    {
        getline(in, currentName, '-');

        // same code past here
    }

I figured changing the while loop condition to the actual getline of the first item in the text file would work, but now when I look at it through the debugger, on the second loop it sets tempString1 to "Vegetable Pot Pie" rather than the next name on the next line. Ironically though this one does fine on line #1, but not for the rest of the list. Overall I feel like this has gotten me farther from my intended behavior than before.

标签: c++filestreamgetline

解决方案


您需要在读取行内容后对其进行解析。您可以使用 astd::istringstream来帮助您。

while(getline(in, line)) 
{
    // At this point, the varible line contains the entire line.
    // Use a std::istringstream to parse its contents.

    std::istringstream istr(line);

    getline(istr, tempString1, '-');  // Use istr, not in.
    getline(istr, currentName, '-');  //    ditto 

    ...
}

推荐阅读