检测新行c ++ fstream

时间:2013-08-19 22:32:54

标签: c++ fstream file-io

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

用户输入“apple”

例如: 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 << " ";
    }
}
你能帮助我吗?实际上,我还会检查检索到的单词与用户指定的单词是否相同,然后我不会在新文件中写入该单词。所以一般来说,它会删除与用户指定的单词相同的单词。

3 个答案:

答案 0 :(得分:8)

逐行方法

如果您仍希望逐行执行此操作,则可以使用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;
    }
}

答案 1 :(得分:2)

有一种更容易的方法来完成这项工作:

#include <fstream>

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

    outFile << inFile.rdbuf();
}

答案 2 :(得分: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";
    }
}