In: Computer Science
In this lab, you open a file and read input from that file in a prewritten C++ program. The program should read and print the names of flowers and whether they are grown in shade or sun. The data is stored in the input file named flowers.dat.
Instructions
FLOWERS
Astilbe
Shade
Marigold
Sun
Begonia
Sun
Primrose
Shade
Cosmos
Sun
Dahlia
Sun
Geranium
Sun
Foxglove
Shade
Trillium
Shade
Pansy
Sun
Petunia
Sun
Daisy
Sun
Aster
Sun
GIVEN CODE
// Flowers.cpp - This program reads names of flowers and whether they are grown in shade or sun from an input
// file and prints the information to the user's screen.
// Input: flowers.dat.
// Output: Names of flowers and the words sun or shade.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Declare variables here
// Open input file
// Write while loop that reads records from file.
fin >> flowerName;
// Print flower name using the following format
//cout << var << " grows in the " << var2 << endl;
fin.close();
return 0;
} // End of main functio
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// main function definition
int main()
{
// Declare variables here
string flowerName, growsIn;
// Open input file
ifstream fin;
fin.open("flowers.dat");
// Checks if the file unable to open for reading display's error
message and stop
if(!fin)
{
cout<<"\n ERROR: Unable to open the file flowers.dat for
reading.";
return 1;
}// End of if condition
// Write while loop that reads records from file.
// Loops till end of the file
while(!fin.eof())
{
// Reads the flowers name and grows
fin >> flowerName;
fin >> growsIn;
// Print flower name using the following format
cout << flowerName << " grows in the " << growsIn
<< endl;
}// End of while loop
// Close the file
fin.close();
return 0;
} // End of main function
Sample Output:
Astilbe grows in the Shade
Marigold grows in the Sun
Begonia grows in the Sun
Primrose grows in the Shade
Cosmos grows in the Sun
Dahlia grows in the Sun
Geranium grows in the Sun
Foxglove grows in the Shade
Trillium grows in the Shade
Pansy grows in the Sun
Petunia grows in the Sun
Daisy grows in the Sun
Aster grows in the Sun
flowers.dat file contents
Astilbe
Shade
Marigold
Sun
Begonia
Sun
Primrose
Shade
Cosmos
Sun
Dahlia
Sun
Geranium
Sun
Foxglove
Shade
Trillium
Shade
Pansy
Sun
Petunia
Sun
Daisy
Sun
Aster
Sun