I saved the file \"test.txt\" in the following format in the same directory as t
ID: 3644689 • Letter: I
Question
I saved the file "test.txt" in the following format in the same directory as the program1.3
2.3
1.2
3.45
6.78
2.34
The program just keeps running, no cmd prompt. no errors.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inputfile;
inputfile.open("test.txt");
double sum = 0,value;
int count=0;
while(!inputfile.eof())
{
inputfile >> value;
sum+= value;
count++;
}
double avg = sum/count;
cout << "The Average of the numbers : " << avg << endl;
system("pause");
return 0;
}
Explanation / Answer
You forgot to check if file opened successfully and to close it after. Also make sure you create a file called "test" that is txt file in directory instead of "test.txt" I ran this code, it should work. #include #include using namespace std; int main() { ifstream inputfile; inputfile.open("test.txt"); double sum,value; int count; count = sum = value = 0; if (inputfile.is_open()) { while(!inputfile.eof()) { inputfile >> value; sum+= value; count++; } double avg = sum/count; coutRelated 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.