Skip to content

Instantly share code, notes, and snippets.

@Rhomboid
Created November 11, 2012 06:34
Show Gist options
  • Save Rhomboid/4053954 to your computer and use it in GitHub Desktop.
Save Rhomboid/4053954 to your computer and use it in GitHub Desktop.
Simple file reading
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <cstdlib>
using namespace std;
static unsigned binary_string_to_int(const string &s)
{
unsigned converted = 0;
for(string::const_iterator it = s.begin(); it != s.end(); ++it) {
if(*it != '0' && *it != '1')
continue;
(converted *= 2) += *it - '0';
}
return converted;
}
int main()
{
ifstream in("input.txt");
if(!in) {
cerr << "error: can't open input.txt" << endl;
exit(1);
}
string line;
while(getline(in, line)) {
istringstream ss(line);
string op, val;
if(ss >> op >> val) {
cout << "got operator [" << op << "] and integer value [" <<
binary_string_to_int(val) << "]" << endl;
} else {
cerr << "malformed input: " << line << endl;
}
}
}
NOT 10100110
AND 00111101
OR 1011
XOR 11011100110111
$ g++ -Wall -Wextra -pedantic -std=c++98 -O2 20121110.cpp -o 20121110
$ ./20121110
got operator [NOT] and integer value [166]
got operator [AND] and integer value [61]
got operator [OR] and integer value [11]
got operator [XOR] and integer value [14135]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment