【问题标题】:Why does my C++ application consume too much system resources and not respond?为什么我的 C++ 应用程序消耗太多系统资源而没有响应?
【发布时间】:2021-10-14 03:59:08
【问题描述】:

我想在文本文件中搜索一个字符串。我使用 CodeBlocks 作为 IDE。

这是我的代码:

string strLineToRead;

ifstream ifFile;
ifFile.open("FileToRead.txt");

while(strLineToRead.find("blabla") == string::npos)
{
     getline(ifFile, strLineToRead);
}

ifFile.close();

return 0;

【问题讨论】:

  • 你应该学习如何调试你的代码。
  • 在文件不包含字符串“blablah”的情况下,该程序将如何摆脱while 循环?

标签: c++ file ifstream


【解决方案1】:

你的代码中有一个while循环,如果你的条件不满足会导致很多资源,在这种情况下是strLineToRead.find("blabla") == string::npos,如果发生这种情况,你将进入一个无限循环。考虑将您的条件更改为此while(getline(ifFile, strLineToRead)) 也可以考虑用打开方式打开文件,减少资源。

【讨论】:

    【解决方案2】:

    Below 是一个工作示例/演示,展示了如何在文本文件中查找给定字符串:

    ma​​in.cpp

    #include <iostream>
    #include <fstream>
    
    int main()
    {
        
        std::string line, stringtobeSearched = "blabla";
    
        std::ifstream inFile("input.txt");
        
        
        if(inFile)
        {
            while(getline(inFile, line, '\n'))        
            {
                //std::cout<<line<<std::endl;
                //if the line read does not contain the string searched for 
                if(line.find(stringtobeSearched) == std::string::npos)
                {
                   ; //do something here
                }
                //if the line read contains the string searched for then print string  found
                else 
                {
                    std::cout<<"string found "<<std::endl;
                }
                
                
            }
        }
        else 
        {
            std::cout<<"file could not be read"<<std::endl;
        }
        inFile.close();
        
        
       
        return 0;
    }
    

    input.txt

    this is first line 
    this is second blabla
    third line is this 
    blabla again found for second time 
    

    上述程序的输出如下(here):

    string found 
    string found
    

    【讨论】:

    • 我认为您的代码有错误。 “!= string::npos” 表示“找到字符串。”,“== string::npos” 表示“未找到字符串。”
    • 是的,感谢您发现错字。
    【解决方案3】:

    我相信你只是打错了。但我无法控制自己,我喜欢编码。 所以……这是我的尝试:

    auto infile = std::ifstream("./file.txt");
    
    for (auto line = std::string(); std::getline(infile, line); ) {
      if (std::string::npos != line.find("blabla")) {
        std::puts("Found it.");
        return {};
      }
    }
    
    std::puts("Nope.");
    

    Compiler explorer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-15
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      相关资源
      最近更新 更多