Write a main( ) routine in which the program will request the user to enter a fi
ID: 673523 • Letter: W
Question
Write a main( ) routine in which the program will request the user to enter a file name, then attempt to open the file with that name. If the file does not exist, display an error message. It the file docs exist but contains NO data, display an error message. If the file does exist and contains data then your program calls a function that has the following interface: Inside method numIntElement, the code should read all the integers in the file and return the total number of integers stored in that file. You must design a while loop with a test for end-of-file (cof) condition: x.cof( ), where cof( ) represents the end of a file and is a member function of fstream class. You must run tests to verify the correctness of your program. The file "in.dat" should be downloaded from Canvas and be part of the testing of the program. Use the project template for EACH program - they can be combined into one document OR be uploaded as individual documents.Explanation / Answer
#include <iostream>
#include<fstream>
using namespace std;
int numIntElement(ifstream &x) {
int sum = 0;
while (!x.eof())
{
int temp;
x >> temp;
sum += temp;
}
return sum;
}
int main() {
string fileName;
string line;
cout<<"Enter a file name: ";
cin>>fileName;
ifstream myfile (fileName);
if (myfile.is_open())
{
if ( myfile.peek() == std::ifstream::traits_type::eof() )
{
cout<<"Empty file !!!";
}
cout<<"Total of integers in file is: "<<numIntElement(myfile);
myfile.close();
}
else cout << "Unable to open file !!!";
return 0;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.