Read a .txt file, calculate sum and mean - c++

I have a .txt file which contains numbers and looks like this:
1
2
3
etc
The numbers are unimportant but they all start on a new line.
I want to then find the sum & mean of the numbers in the text file.
Here's what I have so far:
#include<cmath>
#include<cstdlib>
#include<iomanip>
#include<string>
#include<fstream>
using namespace std;
int main(int argc, char * argv[])
{
std::fstream myfile("numbers.txt", std::ios_base::in);
float a;
while (myfile >> a)
{
printf("%f ", a);
}
getchar();
return 0;
int sum(0);
int sumcount(0);
double average(0);
int even(0);
int odd(0);
ifstream fin;
string file_name;
int x(0);
cout<<"numbers.txt";
cin>> file_name;
fin.open(file_name.c_str(),ios::in);
if (!fin.is_open())
{
cerr<<"Unable to open file "<<file_name<<endl;
exit(10);
}
fin>>x;
while (!fin.fail())
{
cout<<"Read integer: "<<x<<endl;
fin>>x;
sum=sum+x;
sumcount++;
if(x%2==0)
even++;
else
odd++;
}
fin.close();
average=(double)sum/sumcount;
cout<<"Sum of integers: "<<sum<<endl;
cout<<"Average: "<<average<<endl;
cout<<"Number of even integers: "<<even<<endl;
cout<<"Number of odd integers: "<<odd<<endl;
return 0;
}
The start loads the numbers but it won't execute the next step.
i have looked at a lot of other code and tried to implement other ideas to solve the problem; however, some people use loops and arrays and other things and I'm not sure which to use.
How can I get my program to find the sum and mean of numbers in the file?
also any other links for help would be appreciated
EDIT: although the numbers are intergers the mean may not be

Here is your working code.
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char * argv[])
{
std::fstream myfile("numbers.txt", std::ios_base::in);
float a = 0;
myfile >> a;
while (!myfile.fail())
{
printf("%f ", a);
myfile >> a; // here you dispay your numbers
}
getchar(); // waiting for input
float sum(0);
int x(0);
int sumcount(0);
double average(0);
int even(0);
int odd(0);
ifstream fin;
string file_name;
cout<<"numbers.txt" << endl;
cin>> file_name; // waiting for enter file name
fin.open(file_name.c_str(),ios::in);
if (!fin.is_open())
{
cerr<<"Unable to open file "<<file_name<<endl;
exit(10);
}
fin >> x;
while (!fin.fail())
{
cout<<"Read integer: "<<x<<endl; // display number again
sum=sum+x;
sumcount++;
if(x % 2==0) // compuing your file statistics
even++;
else
odd++;
fin>>x;
}
fin.close();
average=(double)sum/sumcount;
cout<<"Sum of integers: "<<sum<<endl; // displaying results
cout<<"Average: "<<average<<endl;
cout<<"Number of even integers: "<<even<<endl;
cout<<"Number of odd integers: "<<odd<<endl;
return 0;
}
I have added some minimal alteration to make your program work correctly.
the result
and more

As soon as your main function encounters the statement return 0 it will exit the program and fail to execute the remaining code. This should generally appear only once in your main function, at the end of your code block

#include <iostream>
#include <fstream>
using namespace std;
int main() {
int n=0;
int sum=0,total=0;
fstream file("numbers.txt");
while(file >> n) // or while(cin >> n) to read from stdin, commandline
{
sum += n;
total++;
}
int average = (float) sum/total;
cout<<"sum: " << sum << endl;
cout << "average: " << average << endl;
return 0;
}

#include <iostream>
#include<fstream>
int main()
{
std::ifstream txtFile;
txtFile.open("data.txt");
//TODO: check if the file fails to open.
double tempNum, mean(0.0), sum(0.0), count(0.0);
while (txtFile >> tempNum)
{
sum += tempNum;
++count;
}
mean = sum/count;
std::cout << "mean: " << mean << " sum: " << sum << std::endl;
return 0;
}

Related

Trying to write a program that produces sum of all whitespace-separated integers in a text file

I'm not getting any errors, just an infinite loop! Here's my code:
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
#include<fstream>
#include<assert.h>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main() {
int sum{ 0 }, number;
vector<int> numbers;
string word;
fstream file;
file.open("file1.txt", fstream::in);
while (true) {
file >> number;
if (file.eof()) {
numbers.push_back(number);
break;
}
else if (file.fail()) { file >> word; }
else if (file.bad()) exit(1);
else numbers.push_back(number);
}
for (int x : numbers) sum += x;
cout << sum << "\n";
}
The file I am reading from:
words 32 jd: 5 alkj 3 12 fjkl
23 / 32
hey 332 2 jk 23 k 23 ksdl 3
32 kjd 3 klj 332 c 32
You are not reading the integers properly, or correctly checking if operator>> is successful before using number. And more importantly, you are not clearing the stream's error state when non-integer input is encountered by operator>>.
Try something more like this instead:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
#include <stdexcept>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main() {
int sum = 0, number;
vector<int> numbers;
string word;
ifstream file("file1.txt");
while (file >> word) {
try {
number = stoi(word);
}
catch (const std::exception &) {
continue;
}
numbers.push_back(number);
}
if (file.fail() && !file.eof())
exit(1);
for (int x : numbers)
sum += x;
cout << sum << "\n";
keep_window_open();
return 0;
}
Live Demo
See if this works:
#include<iostream>
#include<fstream>
#include <cctype> // isdigit
#include<string>
#include<vector>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main() {
int sum{ 0 };
string number; // new
vector<int> numbers;
fstream file;
file.open("file1.txt", fstream::in);
while (true) {
file >> number;
if (file.eof())
break;
if (isdigit(number[0])) // new
numbers.push_back(stoi(number));
}
file.close();
for (int x : numbers) sum += x;
cout << sum << "\n";
return 0;
}

How to get the average from data.txt file with C++?

Our professor wants us to fix the code which counts the amount of values in a data.txt file and computes their average. Here is the code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
string s;
ifstream f;
int nItems;
double * data;
double sum=0;
vector < double > data2;
double item;
cout <<"File name: ";
cin >> s;
f.open (s.c_str() );
while (! f.eof() )
{
f >> item;
data2.push_back(item);
}
for (int i =0; i < nItems; i++)
{
sum += data[i];
}
cout << "The average is " << sum/nItems <<".\n";
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
His instructions were:
Modify code worked on today so that the average of data in vector < double > data is computed properly. Right now the code just gives you a value which isn't the average.
I tried changing the nItems variable into 12 and that seemed to work, but the goal of the code is to determine nItems and use that to find the average, which I can't seem to figure out.
You use data for which you haven't allocated any memory when you summarise That causes undefined behaviour. You've stored your values in data2. Remove variables you don't need. Also, using namespace std is considered bad practice.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <numeric> // std::accumulate
int main(int, char**) {
std::string filename;
std::cout << "File name: ";
std::cin >> filename;
std::ifstream f(filename); // no need for .c_str()
std::vector<double> data;
double item;
// instead of checking for eof, check if extraction succeeds:
while(f >> item) {
data.push_back(item);
}
// a standard way to sum all entries in a container:
double sum = std::accumulate(data.begin(), data.end(), 0.);
std::cout << "The sum is " << sum << "\n";
// use the containers size() function. it returns the number of items:
std::cout << "The average is " << (sum / data.size()) << "\n";
}
Hey looks like you weren't reading the numbers in from the txt file.
Here I look through the input file once just to count how many numbers there are
so I can make the array.
Then I look through it again to fill the array.
#include <cstdlib>
#include <iostream>
#include <fstream>
// f here stands for find, fstream gives you files
using namespace std;
int main(int argc, char *argv[]) {
string s;
ifstream f;
// input file stream
int nItems;
double * data;
double sum=0;
cout << "File name: ";
cin >> s;
f.open (s.c_str() );
// s.c_str will return a char array equivalent of the string s
nItems=0;
int input =0;
while (f >> input) {//first loop reading through file to count number of items
nItems++;
}
f.close();
data = new double[nItems]; //Make the array
f.open (s.c_str() );//open file for second read
int i=0;
while (f >> input) {//Second loop through file fills array
data[i] = input;
i++;
}
f.close();
for (int i = 0; i < nItems; i++) {
sum += data[i];
}
cout << "The average is " << sum / nItems << ".\n";
cout << endl;
system("pause");
return 0;
}

I want to calculate total and average of data from text file using C++

I want to calculate total and average of data from text file using C++.
Here is my code and text file.
This code is not showing anything on run
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;
string double2string(double);
double string2double(string);
int main(int argc, char* argv[]){
fstream dfile;
string s1;
string amount;
double damount;
double sum = 0;
dfile.open(argv[1]);
dfile >> amount;
damount = string2double(amount);
while(damount){
sum = sum + damount;
}
string total = double2string(sum);
dfile.clear();
dfile.close();
cout << total;
return 0;
}
Functions to convert string to double and double to string
string double2string(double d){
ostringstream outstr;
outstr << setprecision(2) << fixed << setw(10) << d;
return outstr.str();
};
double string2double(string s1){
istringstream instr(s1);
double n;
instr >> n;
return n;
}
Here is my text file "data.txt"
234
456
789
You need to use a while loop. You're reading in only one line, so you need to make sure that you keep reading in lines until the end of the file.
Also, you might want to use a standard library function: std::stoi is the C++11 and onward version that works for std::string, but std::atoi from <cstdlib> works just as well with std::string.c_str().
#include <iostream>
#include <fstream>
#include <string>
//Compile with C++11; -std=c++11
int main(int argc, char** argv) {
std::fstream file;
//Open the file
file.open(argv[1]);
std::string buffer = "";
int sum = 0;
int n = 0;
//Check for file validity, and keep reading in line by line.
if (file.good()) {
while (file >> buffer) {
n = std::stoi(buffer);
sum += n;
}
std::cout << "Sum: " << sum << std::endl;
} else {
std::cout << "File: " << argv[1] << "is not valid." << std::endl;
}
return 0;
}

C++ Getting values from file into array

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;
void make_array(ifstream& num, int (&array)[50]);
int main()
{
ifstream file; // variable controlling the file
char filename[100]; /// to handle calling the file name;
int array[50];
cout << "Please enter the name of the file you wish to process:";
cin >> filename;
cout << "\n";
file.open(filename);
if (file.fail()) {
cout << "The file failed to open.\n";
exit(1);
} else {
cout << "File Opened Successfully.\n";
}
make_array(file, array);
file.close();
return (0);
}
void make_array(ifstream& num, int (&array)[50])
{
int i = 0; // counter variable
while (!num.eof() && i < 50) {
num >> array[i];
i = i + 1;
}
for (i; i >= 0; i--) {
cout << array[i] << "\n";
}
}
I am trying to read values from a file to an array using fstream. When I try to display the contents of the array, I get 2 really big negative numbers, and then the contents of the file.
Any ideas what I did wrong?
Your use of num.get(array[i]) doesn't match any of its signatures. See get method description. What you want is this:
array[i] = num.get();
As discussed in the comments, you try to read an integer which is encoded as text. For this, you need to use operator>> (which reads any type encoded as string) instead of get (which reads a single byte):
num >> array[i];

C++ pyramid of numbers

I need to write a program where it takes 2 integers from a file. Then it has to make a pyramid from those 2 numbers. It has to look like this:
I've wrote the code and it works as I want to, bet I can't think of a way how make it look a pyramid like.
Here's how it looks when I do it:
And this is my code:
#include <fstream>
using namespace std;
int main(){
ifstream inFile("Duomenys.txt");
ofstream outFile("Rezultatai.txt");
int N,M,smth,suma=0;
inFile >> N >> M;
smth=N;
while(N<=M){
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
suma+=i;
if(i==N){
for(int i=N-1;i>=smth;i--){
outFile<<i<<" ";
suma+=i;
}
}
}
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
inFile.close();
outFile.close();
return 0;
}
So my question would be, how to make it that my answer would be shaped in pyramid like in example?
#include <fstream>
#include <iostream>
#include <iomanip>
#include <assert.h>
using namespace std;
template <class T>
int numDigits(T number)
{
int digits = 0;
while (number) {
number /= 10;
digits++;
}
return digits;
}
int main()
{
ifstream inFile("Duomenys.txt");
ofstream outFile("Rezultatai.txt");
int N,M,smth,suma=0;
inFile >> N >> M;
smth=N;
// assuming positive numbers
assert(N>=0 && M>=0);
// this will be the size of each printed number
int nd = numDigits<int>(M)+1;
while(N<=M){
for(int i=N;i<=M;i++)
outFile << setw(nd) << " ";
for(int i=smth;i<=N;i++){
outFile << setw(nd) << i;
suma+=i;
if(i==N){
for(int i=N-1;i>=smth;i--){
outFile << setw(nd) << i;
suma+=i;
}
}
}
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
inFile.close();
outFile.close();
return 0;
}
First you must compute your second number's digit count. It's so easy. Then you can calculate the depth of concluded pyramid using: (second number- first number)+1. After that you can be sure that in the last row, the max digit count you will have is ((second number - first number)*2+1)*digit count=x of pyramid's head. So you should print the head of pyramid at (x,y)=(x of pyramid's head, ....)
To determine the length of the last row you can either write your output to an std::stringstream and get the length with myStrStream.str().size() (and afterwards print the contents of your string stream to std::cout or your outFile) or you can count the length of all items of the last line separately and then sum then up, including spaces. I think the first approach is simpler.
The easiest approach might be backtracking.
This also depends on the digits that every number have.
Assuming that every number has two digits, is enough to add a certain number of space for each iteration.
This number in your case is 5 during the first iteration, and ends up being zero:
#include <fstream>
using namespace std;
int main(){
ifstream inFile("Duomenys.txt");
ofstream outFile("Rezultatai.txt");
int N,M,smth,suma=0;
inFile >> N >> M;
smth=N;
while(N<=M){
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
suma+=i;
if(i==N){
for(int i=N;i<M;i++)
cout << " ";
for(int i=N-1;i>=smth;i--){
outFile<<i<<" ";
suma+=i;
}
}
}
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
inFile.close();
outFile.close();
return 0;
}
An alternative is to use iomanip's setw, but this case you have to write all numbers in a string and print the whole string each time.
#include<fstream>
using namespace std;
ofstream outFile("output");
void printSpace(int a){
string spaces(a,' ');
outFile<<spaces;
}
int main(){
int N=1,M=11,smth=4,suma=0;
int l=2*(M-N);
while(N<=M){
printSpace(l);
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
suma+=i;
if(i==N){
for(int i=N-1;i>=smth;i--){
outFile<<i<<" ";
suma+=i;
}
}
}
l-=2;
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
outFile.close();
return 0;
}
inFile >> N >> M;
smth=N;
while(N<=M){
for(int position=0;position<(M-N);position++){ // doesn't work if M<N obviously
for(int digit=(smth+position);digit;digit=digit/10){
outFile<<" ";
}
outFile<<" "; // this is to complement the spacer for each digit in your code
}
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
...