C :使用getline从文本文件中输入,要么跳过第一行,要么将其余部分弄乱

C++: Using getline to input from a text file either skips the first line or messes up the rest

本文关键字:一行 余部 getline 使用 文本 文件 输入      更新时间:2023-10-16

我正在尝试从特殊格式的文本文件中阅读以搜索特定名称,数字等。在这种情况下,我想阅读第一个数字,然后获取名称,然后进入下一行。我的问题似乎是在循环条件下逐行阅读文件的情况。这是TXT文件格式的示例:

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 

我将向您展示我尝试过的两个解决方案,一种跳过文件中的第一行,另一行不在最后一行中。我尝试过典型的while(!

    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;
            }
        }

我相信我知道这是什么。" getline(in in,in Line("完全占据了第一行,并且由于我不使用它,因此它实际上是被跳过的。至少,它是第一个数字,其次是名称,然后正确执行操作。以下是对代码的修改。

    while(getline(in, tempString1, '-'))
    {
        getline(in, currentName, '-');
        // same code past here
    }

我认为将while循环条件更改为文本文件中第一个项目的实际获取线,但是现在,当我通过调试器查看它时,在第二个循环中,它将tempstring1设置为"蔬菜锅派"比下一行上的下一个名字。具有讽刺意味的是,尽管这在第1行上表现不错,但对于其余的列表而言不行。总的来说,我觉得这比我的预期行为更远。

您需要在读取线条后解析行内容。您可以使用std::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 
    ...
}