Answer the question
In order to leave comments, you need to log in
How to properly organize file input?
The book has a code example demonstrating file input, but unfortunately what is described in the code does not correspond to the result described in the same book.
In general, there is this code:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <cstdlib>
const int size = 60;
int main()
{
char filename[size];
std::ifstream in;
std::cout << "Enter name of data file: ";
std::cin.getline(filename, size);
in.open(filename);
if (!in.is_open())
{
std::cout << "Could not open the file " << filename << std::endl;
std::cout << "Program terminating.\n";
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;
in >> value;
count++;
sum += value;
std::cout << "value: " << value << ", sum: " << sum << std::endl;
while (in.good())
{
in >> value;
count++;
sum += value;
std::cout << "value: " << value << ", sum: " << sum << std::endl;
}
if (in.eof())
std::cout << "End of file reached.\n";
else if (in.fail())
std::cout << "Input terminated by data mismatch.\n";
else
std::cout << "Input terminated for unknown reason.\n";
if (count == 0)
std::cout << "No data processed.\n";
else
{
std::cout << "Items read: " << count << std::endl;
std::cout << "Sum: " << sum << std::endl;
std::cout << "Average: " << sum / count << std::endl;
}
in.close();
system("PAUSE");
return 0;
}
in >> value;
while (in.good())
{
++count;
sum += value;
in >> value;
}
in >> value;
count++;
sum += value;
std::cout << "value: " << value << ", sum: " << sum << std::endl;
while (in.good())
{
in >> value;
count++;
sum += value;
std::cout << "value: " << value << ", sum: " << sum << std::endl;
}
Answer the question
In order to leave comments, you need to log in
Hello.
I offer my own solution based on the string class
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string namefile; cout << "Enter name of file: ";
cin >> namefile;
namefile += ".txt"; cout << endl;
ifstream Q(namefile); string temporary;
double summary{ 0 }; unsigned items{ 0 };
while (Q >> temporary)
{
summary += stod(temporary);
items++;
cout << "Value: " << stod(temporary);
cout << endl<< "Current summary: " << summary << endl;
cout << endl<<endl<<endl; temporary.clear();
}
cout << "We have reached the edge." << endl << endl;
cout << items << " items have just read" << endl << endl;
cout << "Summary: " << summary << endl << endl;
cout << "Average: " << (summary / items);
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question