Opening files and performing file input Opening Files and Performing File Input.
ID: 667383 • Letter: O
Question
Opening files and performing file input
Opening Files and Performing File Input. Then modify the program so that it takes the text read from flowers.dat and writes it to a new file named flowers2.dat. Submit the revised flowers.cpp file.
1.Open the source code file named flowers.cpp using notepad.
2.Declare variable you will need
3.Write C++statement that will open the input file flowers.dat reading
4.Write a while loop to read the input until EOF is reached
5.In the body of the loop, print the name of each flower and where it can be (sun or shade)
6.Save this source code file in a directory and make that directory your working directory
7.Compile the source code file flowers.cpp
8.Execute the program
(This is the flower.cpp code which need to modify)
//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
fin.close();
return 0;
} // End of main function
Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
void readfile(string filename){
ifstream infile;
infile.open(filename.c_str());
string s;
// Read till end of file
while (!infile.eof()){
getline(infile,s);
// print flower and (shade or sun)
cout << s << endl;
}
infile.close();
}
int main(){
readfile("flower.dat");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.