I am making a read/write to file program that I must include the usage of classes. Unfortunately I cannot get it to work as my main function appears to not be seeing my class member functions. I'm not sure why this is, but I was wondering if anyone could help me.
Errors occur at lines 56, 62 and 82. The compiler states that they are undeclared identifiers, yet they are declared just right above?
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
class ReadWrite
{
public:
void Read(istream& infile);
void Write(ostream& infile);
};
void ReadWrite::Read(istream& infile)
{
string line;
while(getline(infile,line))
{
cout << line << endl;
}
}
void ReadWrite::Write(ostream& infile)
{
string input;
while(input != "save"){
getline(cin,input);
if(input == "save")
{
break;
}
infile << input << endl;
}
}
int main()
{
string userinput;
cout << endl << "Hi, this program will search for your specified file that you may read or write to. You may also create a new file when asked. Also note you can exit the program at any time by typing 'quit'" << endl << endl;
while(userinput != "quit")
{
cout << "What is the name of your file?" << endl;
cin >> userinput;
fstream file(userinput, ios::app);
if(!file.is_open())
{
cout << "Would you like to read or write to this file?" << endl;
cin >> userinput;
if(userinput == "read")
{
Read(file);
}
if(userinput == "write")
{
cout << "You may now write, enter 'save' when you wish to exit the writing process." << endl;
Write(file);
}
}
else
{
cout << "File does not exist, would you like to write a new one? (Yes/No)" << endl;
cin >> userinput;
if(userinput == "Yes")
{
cout << "Please enter the name of your file, include .txt extension." << endl;
cin >> userinput;
fstream newFile(userinput);
newFile.open(userinput, ios::out);
cout << "You may now write to your new file, enter 'save' when you wish to exit the writing process." << endl;
Write(newFile);
}
if(userinput == "No")
{
cout << "Would you like to search for a new file? If Yes, you can enter a new file name, if No the program will exit." << endl;
if (userinput == "Yes")
{
continue;
}
if(userinput == "No")
{
userinput = "quit";
}
else{
cout << "You've entered an incorrect response. Please try again." << endl;
}
}
}
}
return 0;
}
Ah yes Eyenrique! That does indeed fix it! Thank you... I could of swore last time I programmed in C++ that I didn't need an instance. In fact I look at old programs I made and I didn't have to use an instance in some cases and the program worked. So why must I need an instance here?
To be honest i
do not know old
C++ standard i
learned that you
have to create an instance
when you want an user-defined type
but you can access to
member functions and
data members without
instances using a certain
syntax;
Eyenrique-MacBook-Pro:Desktop Eyenrique$ ./ClassSyntax
NEXT SERVICE
30 MILES
NEXT SERVICE
30 MILES
NeXT SERVICE
30 MILES