Detect new line c++ fstream -


how read .txt copy content .txt using fstream similar content. problem is, when in file there new line. how detect while using ifstream?

user enter "apple"

eg: note.txt => bought apple yesterday. apple tastes delicious.

note_new.txt => bought yesterday. tastes delicious.

the resulting note suppose above, instead: note_new.txt => bought yesterday. tastes delicious.

how check if there new line in source file, create new line in new file.

here 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 me? check when word retrieved same user specified, won't write word in new file. general, delete words same 1 specified user.

line-by-line method

if still want line-by-line, 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 line stream , rewrite wherever want.


easier method

if want rewrite 1 file inside other one, use rdbuf :

#include <fstream>  using namespace std;  int main() {     ifstream infile ("note.txt");     ofstream outfile("note_new.txt");      outfile << infile.rdbuf(); //  ^^^^^^^^^^^^^^^^^^^^^^^^^^ } 

edit : permit remove words don't want in 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"); // 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;     } } 

Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -