【问题标题】:If a line contains certain Word save it如果一行包含某些 Word 保存它
【发布时间】:2012-02-04 07:52:11
【问题描述】:
#include <iostream>
#include <fstream>

using namespace std;

int main()
{

    ifstream  stream1("source.txt");
    string line ;
    ofstream stream2("target.txt");

        while( std::getline( stream1, line ) )
        {
                stream2 << line << endl;
                cout << line << endl;
        }


    stream1.close();
    stream2.close();    return 0;
}

我怎样才能使这个代码使它成为这样,如果它在一行中找到例如“HELLO”的单词,它将保存到整个行的stream2中?如果没有该单词,其余行将不会保存到 stream2。

基本上,如果它在阅读时在一行中找到“HELLO”一词。它输出它。如果没有,则跳过该行。

【问题讨论】:

  • 您的问题是如何测试字符串是否出现在行中?或者如何写入输出流?一旦你知道如何做到这两点,这应该是微不足道的。
  • 不能直接回答您的问题,但您知道“grep”吗?
  • 基本上如果它在阅读时在一行中找到单词“HELLO”。它输出它。如果没有,则跳过该行。

标签: c++ input fstream


【解决方案1】:
while( std::getline( stream1, line ) )
{
    if(line.find("hello") != string::npos)
        stream2 << line << endl;

    cout << line << endl;
}

【讨论】:

  • 这很好用。我不知道它有一个 .find 部分
猜你喜欢
  • 2014-01-24
  • 2015-08-15
  • 1970-01-01
  • 2011-09-12
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
  • 1970-01-01
  • 2016-03-11
相关资源
最近更新 更多