Skip to content

Instantly share code, notes, and snippets.

@1f0
Last active February 20, 2019 13:45
Show Gist options
  • Save 1f0/3aac65ac2411427a37f850917d56f121 to your computer and use it in GitHub Desktop.
Save 1f0/3aac65ac2411427a37f850917d56f121 to your computer and use it in GitHub Desktop.
basic c++ read file
#include <iostream>
#include <exception>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char const *argv[]) {
if (argc < 2) {
cout << "Usage: " << argv[0] << " filename.txt" << endl;
return 0;
}
ifstream fs(argv[1]);
string line;
int sum = 0;
if (fs.is_open()) {
while (getline(fs, line)) {
try {
int x = stoi(line);
sum += x;
} catch(exception& e) {
cout << "\"" << line << "\" parse failed." << endl;
cout << "in function " << e.what() << endl;
return 0;
}
}
cout << "sum: " << sum << endl;
} else {
cout << "open file " << argv[1] << " failed." << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment