-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathreadfile.cpp
More file actions
43 lines (34 loc) · 916 Bytes
/
Copy pathreadfile.cpp
File metadata and controls
43 lines (34 loc) · 916 Bytes
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
#include<iostream>
#include<fstream>
#include<sstream>
// Read a file of integers and compute the sum
using namespace std;
int main(int argc, char * argv[]) {
ifstream numberFile;
string buffer;
int 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" << endl;
exit(1);
}
// Open the file
numberFile.open(argv[1]);
if (!numberFile) {
cerr << "Unable to open file " << argv[1] << endl;
exit(2);
}
// Read the file line by line
while (getline(numberFile, buffer)) {
auto lineStream = istringstream(buffer);
// Get each number from lineStream
while(lineStream >> number) {
sum += number;
}
}
cout << "Total = " << sum << endl;
numberFile.close();
return 0;
}