forked from wadehuber/codeexamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreadfile.cpp
More file actions
45 lines (36 loc) · 1.07 KB
/
Copy pathreadfile.cpp
File metadata and controls
45 lines (36 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include<iostream>
#include<fstream>
#include<sstream>
// This program reads integers from a file and computes the sum
using namespace std;
int main(int argc, char * argv[]) {
string buffer;
ifstream numberFile;
string number;
int sum=0;
// CHeck if a filename is passed
if (argc < 2) {
// cerr is like cout but prints to the error stream
cerr << "Missing filename to read\n" << argv[1] << endl;
exit(1);
}
// Open the file
numberFile.open(argv[1]);
if (!numberFile) {
// cerr is like cout but prints to the error stream
cerr << "Unable to open file " << argv[1] << endl;
exit(1);
}
// Read the file line by line
while ( getline(numberFile, buffer) ) {
// An istringstream lets us stream integers from a string
auto lineStream = istringstream{buffer};
// Get each number from the lineStream
while(lineStream >> number) {
sum += stoi(number);
}
}
cout << "Total = " << sum << endl;
numberFile.close();
return 0;
}