// Example: Write a program that sums the 2nd column of a file with 3 columns of numbers
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int sumOf2ndColumnInFile(const string& filename);
int main()
{
cout << sumOf2ndColumnInFile("numbers1.txt") << endl;
cout << sumOf2ndColumnInFile("numbers2.txt") << endl;
return 0;
}
int sumOf2ndColumnInFile(const string& filename)
{
ifstream fin(filename.c_str());
int sum = 0, number, dummy;
if (!fin)
{
cerr << "Can't open " << filename << endl;
exit(1);
}
while (!fin.eof())
{
fin >> dummy >> number >> dummy;
sum += number;
}
return sum;
}
***** OUTPUT *****
23
15
Input Files
numbers1.txt
numbers2.txt