Detect new line c++ fstream

后端 未结 3 770
花落未央
花落未央 2021-01-18 05:18

How do I read a .txt copy the content to another .txt by using fstream to a similar content. The problem is, when in the file there is new line. How do I detect that while u

3条回答
  •  被撕碎了的回忆
    2021-01-18 05:50

    Line-by-line method

    If you still want to do it line-by-line, you can use std::getline() :

    #include 
    #include 
    #include  
    
    using namespace std;
    
    int main() {
        ifstream inFile ("note.txt");
        string line;
        //     ^^^^
        ofstream outFile("note_new.txt");
    
        while( getline(inFile, line) ) {
        //     ^^^^^^^^^^^^^^^^^^^^^
            outfile << line << endl;
        }
    }
    

    It gets a line from the stream and you just to rewrite it wherever you want.


    Easier method

    If you just want to rewrite one file inside the other one, use rdbuf :

    #include 
    
    using namespace std;
    
    int main() {
        ifstream inFile ("note.txt");
        ofstream outFile("note_new.txt");
    
        outFile << inFile.rdbuf();
    //  ^^^^^^^^^^^^^^^^^^^^^^^^^^
    }
    

    EDIT : It will permit to remove the words you don't want to be in the new file :

    We use std::stringstream :

    #include 
    #include 
    #include 
    #include  
    
    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;
        }
    }
    

提交回复
热议问题