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
There's a much easier way to do the job:
#include <fstream>
int main() {
std::ifstream inFile ("note.txt");
std::ofstream outFile("note_new.txt");
outFile << inFile.rdbuf();
}
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.
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 <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;
}
}
If you want to remove text from the input file (as your description suggests but does not state).
Then you need to read line by line. But then each line needs to be parsed word by word to make sure you can remove the work you are looking for 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";
}
}