【问题标题】:Find in C++ if a line from file contains a specific character如果文件中的一行包含特定字符,则在 C++ 中查找
【发布时间】:2015-10-15 15:47:59
【问题描述】:

我已经从文本文件中读取了这些行,我想检查该行是否包含 $ 符号。

这就是我目前得到的:

int main() {

    ifstream data_store;
    string line;
    data_store.open("c:\\test.txt");


    while (!data_store.eof())
    {

        getline(data_store, line);
        if (line.find("$"))
        cout << "1: " << line << endl;
    }


    data_store.close();

    system("PAUSE");
    return 0;
}

此外,我如何将它们输出到文件中?

【问题讨论】:

  • 您对查找部分有疑问吗?
  • 然后呢?是有问题还是你只是问如何输出到文件?
  • 我不使用 c++ 我不知道它是将整个字符串与“$”进行比较还是在 line.find 函数中搜索它
  • 使用std::ofstream 写入文件。
  • "它没有找到带有 $ 的行" - 嗯?你有错误,但这根本不是真的。

标签: c++ filestream


【解决方案1】:

使用std::string::find 检查一行是否包含某些内容需要检查来自find 的返回值以确保它是有效返回。为此,我们将它与std::string::npos 进行比较,因为如果它没有找到任何东西,find() 将返回。这就是它发现每一行都为std::string::npos 在评估为bool 时仍然被认为是真的原因。所以重构你的代码:

while (getline(data_store, line))
{
    if (line.find("$") != std::string::npos)
        cout << "1: " << line << endl;
}

我还更改了 while 循环,因为使用 eof 不是如何控制 while 循环。有关更多信息,请参阅Why is “while ( !feof (file) )” always wrong?

至于将字符串输出到文件,请参见:How to write std::string to file?

【讨论】:

    【解决方案2】:

    这是一件小事,但@NathanOliver 解决方案的一个变体是使用for 循环:

    ifstream data_store("c:\\test.txt");
    
    for ( string line; getline(data_store, line); ) {
      if ( line.find("$") != string::npos )
        cout << "1: " << line << endl;
    }
    // ...
    

    这里的好处是line 现在只在循环中是本地的,这是应该的,因为这是唯一使用它的地方。

    【讨论】:

      【解决方案3】:

      昨天做了,忘记更新了。

        #include <iostream>
          #include <fstream>
          #include <string>
      
      using namespace std;
      
      bool contains_number(const string &c);
      
      
      
      int main()
      {
          int count = 0;
          {
              string line1[100];
              ifstream myfile("D:/Users/Jarvan/Desktop/test.txt");
      
              int a = 0;
      
              if (!myfile)
              {
                  cout << "Error opening output file" << endl;
                  system("pause");
                  return -1;
              }
      
              while (!myfile.eof())
              {
                  getline(myfile, line1[a], '\n');
      
                  if (contains_number(line1[a]))
                  {
                      count += 1;
                      cout << line1[a] << "\n";
                  }
                  else cout << "\n";
              }
          }
      
          cout << count <<endl;
      
      
          system("pause");
          return 0;
      }
      
      
      
      bool contains_number(const string &c)
      {
          return (c.find_first_of("$") != string::npos);
      }
      

      【讨论】:

        猜你喜欢
        • 2022-08-02
        • 1970-01-01
        • 1970-01-01
        • 2016-01-11
        • 2021-02-25
        • 1970-01-01
        • 1970-01-01
        • 2017-11-29
        • 1970-01-01
        相关资源
        最近更新 更多