检测新行 c fstream

新手上路,请多包涵

如何通过使用 fstream 将内容复制到另一个 .txt 来读取 .txt 到类似内容。问题是,当文件中有新行时。使用 ifstream 时如何检测到这一点?

用户输入“苹果”

例如:note.txt => 我昨天买了一个苹果。苹果尝起来很好吃。

note_new.txt => 我昨天买了一个。味道鲜美。

生成的注释假设在上面,而是:note_new.txt => 我昨天买了一个。味道鲜美。

如何检查源文件中是否有新行,它也会在新文件中创建新行。

这是我当前的代码:

 #include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    ifstream inFile ("note.txt");
    string word;
    ofstream outFile("note_new.txt");

    while(inFile >> word) {
        outfile << word << " ";
    }
}

你们都可以帮帮我吗?实际上,我还会检查检索到的单词何时与用户指定的单词相同,然后我不会在新文件中写入该单词。所以一般来说,它会删除与用户指定的单词相同的单词。

原文由 muhihsan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 473
2 个回答

逐行法

如果您仍想逐行执行,可以使用 std::getline()

 #include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    ifstream inFile ("note.txt");
    string line;
    //     ^^^^
    ofstream outFile("note_new.txt");

    while( getline(inFile, line) ) {
    //     ^^^^^^^^^^^^^^^^^^^^^
        outfile << line << endl;
    }
}

它从流中获取一行,您只需在任何您想要的地方重写它。


更简单的方法

如果您只想在另一个文件中重写一个文件,请使用 rdbuf

 #include <fstream>

using namespace std;

int main() {
    ifstream inFile ("note.txt");
    ofstream outFile("note_new.txt");

    outFile << inFile.rdbuf();
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^
}


编辑: 它将允许删除您不想出现在新文件中的单词:

我们使用 std::stringstream

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

using namespace std;

int main() {
    ifstream inFile ("note.txt");
    string line;
    string wordEntered("apple"); // Get it from the command line
    ofstream outFile("note_new.txt");

    while( getline(inFile, line) ) {

        stringstream ls( line );
        string word;

        while(ls >> word)
        {
            if (word != wordEntered)
            {
                 outFile << word;
            }
        }
        outFile << endl;
    }
}

原文由 Pierre Fourgeaud 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您想从输入文件中删除文本(如您的描述所建议但未说明)。

然后你需要逐行阅读。但是随后需要逐字解析每一行,以确保您可以删除您正在寻找的工作 apple

 #include <fstream>
#include <string>

using namespace std;
// Don't do this.

int main(int argc, char* argv[])
{
    if (argv == 1) { std::cerr << "Usage: Need a word to remove\n";exit(1);}
    std::string userWord = argv[1];  // Get user input (from command line)

    std::ifstream inFile("note.txt");
    std::ofstream outFile("note_new.txt");
    std::string   line;

    while(std::getline(inFile, line))
    {
         // Got a line
         std::stringstream linestream(line);
         std::string  word;

         while(linestream >> word)
         {
                // Got a word from the line.
                if (word != userWord)
                {
                     outFile << word;
                }
         }
         // After you have processed each line.
         // Add a new line to the output.
         outFile << "\n";
    }
}

原文由 Martin York 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题