Re: Copy, Translate, and Save Text File
Thank you for your help Ike, and the others who have helped me make progres=
s on this.
The attached code (without the indented code in the middle - see below) wor=
ks to read a user-entered text file and then output values from the map to =
a new text file. However, I need to make a copy of the user input file firs=
t, because I want to modify its contents, and I don't want to risk damaging=
the original file. (I want to remove the first five characters from each l=
ine of nine characters in the input file before testing them against the ma=
p. I also have to deal with a header in the input file, but that is too muc=
h for me right now.)
When I added the code to copy the file (indented in middle of code attached=
below), it copied the file to a new file as intended, but then the map rou=
tine, which worked fine without the new code, returned the error "Sorry '' =
Not in move list." How can I fix the code so that both parts work to (1) co=
py the input file to a new file, and (2) return the map values to the outpu=
t file?
Thanks for your help.
#include <iostream>
#include <map>
#include <string>
#include <fstream>
using namespace std;
int main()
{
std::map<std::string, std::string> move_list;
move_list["XXXXXXXXX"] = "ABCD";
move_list["YYYYYYYYY"] = "EFGH";
move_list["ZZZZZZZZZ"] = "IJKL";
for (std::map<std::string, std::string>::const_iterator ci = move_list.b=
egin();
ci != move_list.end();
ci++
)
std::cout << (*ci).first << ' ';
std::cout << std::endl;
std::string TXT;
//New code to ask user for file name
ifstream myfile;
string line;
ofstream copyfile ("Outputfile.txt");
cout << "Please enter the input file name and location> " << flush;
while (true)
{
myfile.close();
myfile.clear();
string myfilename;
getline( cin, myfilename );
myfile.open( myfilename.c_str() );
if (myfile) break;
cout << "Invalid file. Please enter a valid input file name and locatio=
n> " << flush;
}
if (myfile.is_open())
//New code to copy input file to new file
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
{
copyfile << line << endl;
}
}
}
else cout << "Unable to open file";
//end of new code to copy input file
{
while(getline (myfile,TXT))
{
std::ofstream mynewfile ("Testing.TXT", ios::app);
if (mynewfile.is_open())
{
mynewfile << (*move_list.find(TXT)).second <<std::endl;
mynewfile.close();
}
else std::cout << "Unable to open file";
}
myfile.close();
}
else std::cout << "Unable to open file";
if (move_list.count(TXT) == 0)
std::cout << "Sorry, `" << TXT << "' not in move_list.";
else
std::cout << std::endl;
}