Hello. I am begginer and I need your help, because I have tried almost everything possible in my situation and have no idea how to do right way.
My task was following:
in the first text file we have some text, we need to replace all words "sun" to "moon" and write down the result to other text file using fstream function.
My problem is in the cycle of replacing. I was said to look more attentively at my indexes. I did it. Many times, but without result. Here is my code, which works as I want, but with error in the end.
#include <iostream>
#include <fstream>
#include <string>
// using namespace std;
int main()
{
constchar* const in_file_name = "D:\\test_in.txt" ;
constchar* const out_file_name = "D:\\test_out.txt" ;
{
std::ofstream fout(in_file_name); // open file for output
if( !fout.is_open() )
{
std::cerr << "could not open file\n" ;
return 1 ;
}
std::string inT;
std::cout << "Enter your text with word sun \n\n" ;
std::getline( std::cin, inT ) ;
fout << inT << '\n' ;
std::cout << "Text is written" << '\n' ;
// fout is automagically closed when we exit the block
}
{
std::ifstream fin(in_file_name); // open the file for input
std::ofstream fout(out_file_name); // open output file
if( !fin.is_open() || !fout.is_open() )
{
std::cerr << "could not open file\n" ;
return 1 ;
}
const std::string ToFind = "sun";
const std::string ReplaceWith = "moon";
std::string word ;
while( fin >> word ) // for each word in the input file
{
if( word == ToFind ) fout << ReplaceWith << ' ' ; // replace
else fout << word << ' ' ; // do not replace
}
fout << '\n' ; // end with a new line
}
// dump the contents of test_out.txt to stdout
std::cout << "text after replacing: " << std::ifstream("D:\\test_out.txt").rdbuf() ;
}