Search code examples
c++fstreamfile-io

Detect new line c++ fstream


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 using ifstream?

user enter "apple"

Eg: note.txt => I bought an apple yesterday. The apple tastes delicious.

note_new.txt => I bought an yesterday. tastes delicious.

the resulting note suppose to be above, but instead: note_new.txt => I bought an yesterday. tastes delicious.

How do I check if there is a new line in the source file, it also will create new line in new file.

Here is my current code:

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

can you all help me? actually I also check when the word retrieved is the same as what user specified, then I won't write that word in the new file. So it general, it will delete words which are the same as the one specified by user.


Solution

  • Line-by-line method

    If you still want to do it line-by-line, you can use 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;
        }
    }
    

    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 <fstream>
    
    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 <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;
        }
    }