My teacher asked us to create a win32 command line text editor. I have completed the program and it works great. Then he asked us to accept two command line arguments to our program (EX: textedit -f commandts.txt). If the program is started without any arguments then cin is used to get input from keyboard. If the -f commands.txt arguments are used the program should read the input from the file instead of the keyboard. I cannot figure out how to do this. My main looks like this so far:
argc has the number of commandline arguments and argv has the actual arguments. The arguments are separated by a space (?or another delimeter? usually just a space).
It's actually quite easy. Assume you run the program with "textedit -f commands.txt"... you'd have the following:
int main (int argc, char *argv[])
{
string myInput, iFName;
ifstream iFile;
if (argc > 0)
{
if (argv[1] == "-f")
{
iFName = argv[2];
iFile.open(iFName);
}
}
//CONFUSED WHAT TO DO FROM HERE TO MAKE THE FOLLOWING LINE READ FROM FILE INSTEAD OF KEYBOARD WITHOUT CHANGING IT???
getline(cin, myInput);
}
The problem is, my program has 300 lines and all the inputs have been programmed to use cin. The program has to work with either the keyboard OR a file as input. Our teacher did an example in class of how to accomplish this without having to change every cin but I can't remember how he did it.
I know I can do: textedit <commands.txt and that will accomplish what I want but I have to make it work using: textedit -f commands.txt.
You have to go in and change all of your code so that it doesn't use cin. See my earlier post. The only shortcut I can think of is to redefine a new istream variable called 'cin' in the functions that use it -- but that's "very very bad (tm)"
You have just learned the hard lesson of why abstraction is so important. If you use cin directly, then your code always uses cin. If you use an abstract istream reference, then your code will work with any type of istream.
If you can't create a new function for some weird reason, you can use a pointer. This works but is less preferable (the below code will open the file even if the user wants to use cin):