HI, I was trying to learn more about I/O with files in C++ and I can't figure out why this program can't output to the file...
#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
using namespace std;
char userinp;
void print_interface()
{
cout << "Enter E to Encrypt" << endl << "Enter D to Decrypt" << endl;
cout << "Enter R to Erase the file" << endl << "Enter X to Exit" << endl;
}
int main()
{
int cipher = 0, i = 0, iter = 0;
string data[1000];
fstream myfile;
myfile.open("myfile.txt"); // For some reasons this gives me error : myfile.open("myfile.txt", ios::app, ios::in, ios::out);
if(! myfile.is_open()) // It was something about overloaded function can't take 4 arguments...
{
cout << "Could not open the file." << endl;
}
do
{
print_interface();
cin >> userinp;
if (userinp == 'E' || userinp == 'e')
{
system("cls");
cout << "Enter the cipher to user (Number)" << endl;
cin >> cipher;
while(! myfile.eof())
{
getline(myfile, data[iter]);
cout << data[iter];
for(i = 0; i < data[iter].length(); i++)
{
data[iter][i] += cipher;
}
cout << data[iter];
iter++;
}
for(i = 0; i < iter; i++)
{
cout << data[i] << endl;
myfile << data[i] << endl;
}
}
else if (userinp == 'D' || userinp == 'd')
{
}
else if (userinp == 'R' || userinp == 'r')
{
}
else if (userinp == 'X' || userinp == 'x')
{
break;
}
} while(1);
myfile.close();
return 0;
}
What I want this program to do is take input from myfile.txt and then in the end, completely overwrite the data read with the scrambled code. It reads in the data but it can't write to the file. I tried completely erasing the file between the reading and writting part. It didn't make any difference.
This didn't work either :
for(i = 0; i < iter; i++)
{
outfile.open("myfile.txt");
cout << data[i] << endl;
myfile << data[i] << endl;
outfile.close();
}
outfile is ofstream file...