JLBorges' code does everything you requested, so what's the problem...? ;D
Did you want an explanation of where your code failed? Okay *takes out the red marker*
fin.open("flowers.dat");
1. Set your file name to a variable, just like JLBorges did.
2. The constructor of a fstream object auto-magically opens the file, so an explicit open call isn't needed for the first use.
3. Do a boolean comparison on the fstream object itself. If something went wrong and you previously set a variable like file_name, you can then mention it and terminate the program:
1 2 3 4 5 6 7
|
const string file_name("flowers.dat");
ifstream fin(file_name);
if (!fin)
{
cout << "Error: unable to open '"<< file_name << "'. Please check path and make sure file is not in use.\n";
return -1;
}
|
These next few lines are pointless since the
while
loop iterates over the file anyway, assigning every whitespace-separated string anyway. No need to read two strings in advance.
1 2 3 4
|
fin >> flowerName;
fin >> sun_or_shade;
while (!fin.eof()) // Delete this. You got lucky with unbracketed loop not causing more damage --
// it simply executed the next statement, which was a harmless 'if' statement
|
if (fin.is_open())
Ah, the harmless "if" statement. The file has to be open because this line appears
after your outer
while
(which should be deleted). Delete this "if" statement and refactor to the form I presented above.
Then finally your loop that does the work; this all looks good:
while (fin >> flowerName >> sun_or_shade)
HOWEVER, you overrode your previous lines that I called pointless. flowerName was set to "Astilbe" and sun_or_shade was set to "Shade", and here you overwrote these values before ever printing anything to the screen. So then don't be surprised that Astilbe never gets printed
Lastly, you can remove your last line:
fin.close();
because when fin goes out of scope, it automatically closes itself. Since you're not trying to reuse fin for other files, and nothing interesting happens before program terminates anyway, this line can be removed.