#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
**int main()
{
double write();
double read();
string choice;
while(1)
{
cout<<"Enter read to read a file and write to write a file.\n";
cin>>choice;
if (choice == "read")
cout<< read();
if (choice == "write")
cout<< write();
}
}
double read()
{
const int size = 60;
ifstream inFile;
char filename[size];
cout<<"Enter the name of the file you want to read \n";
cin.getline(filename, size);
inFile.open(filename);**
if(!inFile.is_open())
{
cout<<"could not open "<<filename<<endl<<"program terminating";
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;
inFile >> value;
while(inFile.good())
{
cout<<value<<"\n";
++count;
sum += value;
inFile >> value;
}
if (inFile.eof())
cout<<"End of file reached. \n";
else if (inFile.fail())
cout<<"Input Terminated by data mismatch.\n";
else
cout<<"input terminated for unknown reason";
if (count == 0)
cout<<"no data processed";
else
{
cout<<"Items read: "<<count<<endl;
cout<<"Sum: "<<sum<<endl;
cout<<"Average: "<<sum / count << endl;
}
inFile.close();
return 0;
}
double write()
{
char type[81];
char filename[81];
cout<<"this program is more or less pointless, any text edtor on earth is better than this for writing"<<endl;
cout<<"files; However This is the first step in learning how to create my file tranfer program."<<endl;
cout<<"Enter the name of a file you want to create.\n";
cin>>filename;
ofstream outFile;
outFile.open(filename);
outFile<<fixed;
outFile.precision(2);
outFile.setf(ios_base::showpoint);
while(!cin.fail()){
cin.getline(type,81);
outFile<<type<<endl;
}
outFile.close();
}
The problem seems to be that when I type in "read" the program does what its supposed to until it gets to cin>>filename; at which point I think it assigns the value of choice to filename because the program skips to if(!inFile.is_open()){ after I type in "read".(the write function of my program works fine.
could someone please tell me how to solve this problem or another way for the computer to decide weather to choose from functions read or write based on text input.
I am new to C++ so I would appreciate it if the answer is simple, thanks.
P.S. I,m on ubuntu if that makes a difference.