-
Reading from a text file
Ok, so I have the following code, heres the problem. The program involves if/ else if statements, and I need the program to be able to display the help.txt when the user decides to take that route. For some reason, when I do 'h' it is displayed the first time, then if i try the very next time to do 'h' it takes me back to the menu and nothing is displayed. It looks right to me, what am I missing? (i just put the important parts of the program here)
Code:
string file= "help.txt";
string line;
ifstream help;
if (choice =='h')
{//Open choice ==h
help.open (file.c_str());
while (getline(help, line))
cout << line << endl;
help.close ();
}//End choice ==h
-
How do you retrieve choice (which I assume is type char) from your user? are you using without clearing the cin stream before retrieving another value?
-
well, heres what i got basically:
Code:
int main () {
string file= "help.txt";
string line;
ifstream help;
ofstream PC;
int minutes, calc;
double fee;
char choice;
while (choice)
{//Open while
cout << "Help etc etc etc......... Quit" << endl;
cin >> choice;
cin.ignore();
if (choice =='h')
{//Open choice ==h
help.open (file.c_str());
while (getline(help, line))
cout << line << endl;
help.close ();
}//End choice ==h
etc etc etc..........
-
Code:
char choice;
while (choice)
I have a problem with these two lines right away. A good programming practice is to initialize your variables, and this is a perfect example of why.
Since choice is set to NULL, the while loop shouldn't even run once.
Using a do/while loop might be a solution, but maybe you should just initialize choice to some character.
-
I agree - a do/while loop is certainly more suited to this kind of thing than a while loop
-
I did as yall said but still the same problem, the help.txt is only displayed once, but when I try one of my other options multiple times, it works. I think there is something wrong with the way I coded the program to read the txt, any ideas?
-
You wrote the lines just fine.
There is something else I forgot to mention, yes.
It's like the variable help fell out of scope. To keep help in scope, do this:
Code:
if (choice =='h')
{//Open choice ==h
ifstream help;
help.open (file.c_str(), ifstream::out); // enable the file for output just to be sure
while (getline(help, line))
cout << line << endl;
help.close ();
}//End choice ==h
-
You are re-using the help ifstream. The first time through it reads until it errors out (because it reaches the end of the file). The second time through the fail flag is still set, so it doesn't read anything.
The solution is to call clear() to clear the flags in the stream before reading from it.
You don't have to reduce the scope of the ifstream if you call clear, but it would be better practice to use that solution which minimizes the scope of the variable to the block of code that uses it.
-
Great!!! both methods worked thanks ev1 for your help.
hopefully, time to wrap this prog up....