C++.从文本文件读取.每隔一段就缺失一次

C++. Reading from text file. Every second segment is missing

本文关键字:一段 一次 读取 文本 C++ 文件      更新时间:2023-10-16

我在文本文件中有以下数据:

...
A,Q1,1
S,a1,a1
S,a2,a2
S,a3,a3
A,Q1,1
S,b1,b1
S,b2,b2
S,b3,b3
A,Q1,1
S,c1,c1
S,c2,c2
S,c3,c3
A,Q1,1
S,d1,d1
S,d2,d2
S,d3,d3
A,Q2,1
S,x1,x1
S,x2,x2
S,x3,x3
...

我使用以下代码提取数据:

std::string MyClass::getData(const std::string& icao)
{
    // Final String
    std::string finalData = "";
    // Path to the Navigraph Navdata
    std::string path = getPath();
    std::string dataFilePathSmall = navdataFilePath + "ats.txt";
    // Create file streams
    std::ifstream ifsSmall(dataFilePathSmall.c_str());
    // Check if neither of the files exists.
    if (!ifsSmall.is_open())
    {
        // If it does not exist, return Not Available
        finalData = "FILE NOT FOUND";
    }
    // If the file 'ats.txt' exists, pull the data relevant to the passed ICAO code
    if (ifsSmall)
    {
        // We need to look a line starting with the airway prefixed by "A," and suffixed by ','
        const std::string search_string = "A," + icao + ',';
        // Read and discard lines from the stream till we get to a line starting with the search_string
        std::string line;
        // While reading the whole documents
        while (getline(ifsSmall, line))
        {
            // If the key has been found...
            if (line.find(search_string) == 0)
            {
                // Add this line to the buffer
                finalData += line + 'n';
                // ...keep reading line by line till the line is prefixed with "S"
                while (getline(ifsSmall, line) && (line.find("S,") == 0))
                {
                    finalData += line + 'n'; // append this line to the result
                }
            }
        }
        // If no lines have been found
        if (finalData == "")
        {
            finalData = "CODE NOT FOUND";
        }
    }
    // Close the streams if they are open
    if (ifsSmall)
    {
        ifsSmall.close();
    }
    return finalData;
}

现在,我的问题是,由于某种原因,每隔一段数据都没有被读取。也就是说,我收到以下内容:

A,Q1,1
S,a1,a1
S,a2,a2
S,a3,a3
A,Q1,1
S,c1,c1
S,c2,c2
S,c3,c3

我无法弄清楚我的代码中到底缺少什么。提前非常感谢!

while (getline(ifsSmall, line) && (line.find("S,") == 0))

将读取一行并检查它是否以"S"开头。如果它不是以"S"开头,则该行仍已读取。对于您的while+if读取以"A"开头的行也是如此。

内部循环读取不以"S"开头的行,然后终止。这是您缺少的以"A"开头的行。然后,外部循环读取另一行,因此它错过了节的开头。

尝试只使用一个循环和一个 getline((。