7

如何通过使用 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 << " ";
    }
}

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

4

3 回答 3

10

逐行法

如果您仍想逐行执行,可以使用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 <stringstream>
#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;
    }
}
于 2013-08-19T22:38:50.907 回答
2

有一种更简单的方法来完成这项工作:

#include <fstream>

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

    outFile << inFile.rdbuf();
}
于 2013-08-19T22:39:45.997 回答
2

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

然后你需要逐行阅读。但随后需要逐字解析每一行,以确保您可以删除您正在寻找的工作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";
    }
}
于 2013-08-19T22:54:27.270 回答