2017-10-06 97 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"; 
} 

我¹意识到,我可能没有解决的问题相关的,但我觉得这种类型的答案往往是更有益的。使用调试器找到自己的错误的建设性意见也是如此