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