2016-02-14 59 views
-1

我在一個文本文件中的以下數據:C++。從文本文件中讀取。每個第二段丟失

... 
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 

我找不出什麼東西在我的代碼丟失。提前感謝!

+0

爲什麼被拒絕投票?如果你能提供幫助,時間會更有效率。 –

回答

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

將讀取一行並檢查它是否以「S」開頭。如果它不是以「S」開頭,則該行仍然被讀取。如果閱讀以「A」開頭的行,那麼您的時間同樣如此。

+0

謝謝。這現在很合理。試圖找出如何解決這個問題... –

1

內循環讀取不以「S」開頭的行,然後終止。這是以「A」開頭的行。外部循環然後讀取另一行,所以它忽略了部分開始。

嘗試只使用一個循環和一個getline()。

+0

謝謝。不確定在這種特殊情況下,如何僅使用一個循環和getline。 –

+0

其實我不明白你爲什麼需要內循環。它看起來和外循環完全一樣(將當前行追加到一個字符串)。 –

+0

因爲它應該繼續讀取文件,直到必要的前綴在那裏。否則,我不明白所有以「S」開頭的行會如何添加。當段之間有一條空行時,它工作得很好,但這是數據庫現在的樣子,我無法提供幫助。 –

相關問題