2017-10-06 98 views
0

我打開文件並在一行中搜索關鍵字。 如果找到該關鍵字,我會繼續從文件讀取行,直到再次找到文件中的相同關鍵字。它在大多數情況下都能正常工作。但在一種情況下,它不能正常工作。此行getline不能用於打開文件

::MessageBox(NULL, TEXT("here -2"), TEXT(""), MB_OK); 

永遠不會執行時,我檢查。我認爲查找功能從來沒有找到成功。我懷疑getline()函數。我正在看的文本存在於文件中,並且它是帶空格的字符串[如「AB CD EF」]。它作爲行的第一個模式存在,行在文本前沒有空格。可以任何人提示我是什麼錯誤我在C++中是新手。這是我的代碼。

std::ifstream in(curr_file_path); 
std::string search("SEARCH"); 
std::string line; 

char *pDestText = new char[8000*256+1]; 
int f_match = -1; 
int l_match = -1; 
int r_val=0; 
int textLen = 0; 
int flag = 0; 
    while (std::getline(in, line)) 
    { 

     r_val = line.find(search); 
     if (r_val!=(std::string::npos)) 
     { 
      ::MessageBox(NULL, TEXT("here -2"), TEXT(""), MB_OK); 
      f_match = r_val; 

      while (std::getline(in, line)) 
      { 
       ::MessageBox(NULL, TEXT("here -3"), TEXT(""), MB_OK); 
       r_val = line.find(search); 
       if (r_val != std::string::npos) 
       { 
        l_match = r_val; 
        break; 
       } 
       else 
       { 
        ::MessageBox(NULL, TEXT("here -4"), TEXT(""), MB_OK); 
        for (int i = 0; i < line.size(); i++) 
        { 
         pDestText[textLen++] = line[i]; 
        } 
       } 
      } 
      ::MessageBox(NULL, TEXT("here -5"), TEXT(""), MB_OK); 
      for (int i = 0; i < r_val; i++) 
      { 
       //if(line[i]!='=') 
       ::MessageBox(NULL, TEXT("here -6"), TEXT(""), MB_OK); 
       pDestText[textLen++] = line[i]; 
      } 
      //pDestText[textLen] = '\0'; 
      ::MessageBox(NULL, TEXT("here -7"), TEXT(""), MB_OK); 
      break; 
     } 
    } 
    in.close(); 
+3

而當您使用調試器來遍歷代碼時,一次一行地讀取和解析文件,輕鬆檢查這裏顯示的所有變量,在每個步驟中,當有問題的代碼讀取包含搜索字符串的行時,您做了哪些觀察?沒有理由坐在等待stackoverflow.com上的人爲你弄明白,當你能在五分鐘內自己想出來的時候。你應該真的學會如何使用調試器。瞭解如何使用調試器是每個C++開發人員的必備技能。這就是它的目的。 –

+2

Sam是100%正確的!如果你沒有/使用調試器,至少使用一些調試打印,例如:你說'getline'不會工作,把一個'std :: cout << line << std :: endl看到它的內容後...... –

回答

0

我喜歡用乾淨的方式向人們展示標準C++。

Live On Coliru

#include <fstream> 
#include <string> 
#include <iostream> 
#include <iterator> 
#include <sstream> 

// start SEARCH block 

bool filter_lines(std::istream& haystack, std::string const& needle, std::ostream& dest) { 
    bool active = false; 
    std::string line; 

    auto trigger = [&] { 
     bool match = std::string::npos != line.find(needle); 
     if (match) 
      active = !active; 
     return match; 
    }; 

    auto act = [&] { if (active) dest << line << "\n"; }; 

    while (getline(haystack, line)) 
     if (!trigger()) 
      act(); 

    return active; 
} 

int main() { 
    std::ifstream ifs("main.cpp"); 
    std::stringstream destText; 

    if (filter_lines(ifs, "SEARCH", destText)) 
     std::cerr << "Warning: last delimited block unclosed\n"; 

    std::cout << "------------- FILTERED -----------\n" 
       << destText.rdbuf() 
       << "----------------------------------\n"; 
} 

我¹意識到,我可能沒有解決的問題相關的,但我覺得這種類型的答案往往是更有益的。使用調試器找到自己的錯誤的建設性意見也是如此