Thursday, 5 September 2019

Chapter 10 // Exercise 1 - Principles & Practice Using C++

Chapter 10 // Exercise 1

Write a program that produces the sum of all the numbers in a file of whitespace-separated integers.

Main.cpp
//--------------------------------------------//
//main.cpp
//--------------------------------------------//
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <conio.h>
using namespace std;
//create a file with white-space separated integers
void createFile()
{
 ofstream readOut{ "integers.txt" };
 if (!readOut)
  cout << "Error opening file" << endl;
 string integers;
 cout << "Enter a list of whitespace separated integers: (press enter when done)\n>>";
 getline(cin, integers);
 readOut << integers;
}
//read in from a file
vector<int> readInIntegersFromFile()
{
 vector<int> integers;
 ifstream readIn{ "integers.txt" };
 if(!readIn)
  cout << "Error opening file" << endl;
 int temp;
 while (!readIn.eof())
 {
  readIn >> temp;
  integers.push_back(temp);
 }
 return integers;
}
//add numbers together
int sumOfIntegers(vector<int>& v)
{
 int sum = 0;
 for (uint32_t i = 0; i < v.size(); ++i)
  sum += v[i];
 return sum;
}
int main()
{
 createFile();
 vector<int> integers = readInIntegersFromFile();
 int sum = sumOfIntegers(integers);
 cout << "Sum: " << sum << endl;
 cout << "\nPress any key..."; _getch();
 return 0;
}




EDIT: 13/01/2020

No comments:

Post a Comment