validating user input

master
Micke Nordin 13 years ago
parent 1406049fba
commit 52584c266a

@ -27,22 +27,26 @@
using namespace std; using namespace std;
void begin(string needle, istream &in) int begin(string needle, istream &in)
{ {
string input; //This is where we keep our input, line by line string input; //This is where we keep our input, line by line
boost::xpressive::sregex regex = boost::xpressive::sregex::compile( needle, boost::xpressive::regex_constants::icase ); //this is what we search for boost::xpressive::sregex regex = boost::xpressive::sregex::compile( needle, boost::xpressive::regex_constants::icase ); //this is what we search for
if( !in.good() ) { //Check if steam is ok
while(in) { //loop through input line by line cerr << "Could not open file \n";
getline(in, input); return 1; //if not return 1
if ( boost::xpressive::regex_search(input, regex) ) { //if we find a match } else { //go ahead
cout << input << endl; //start printing to std out while(in) { //loop through input line by line
while(in) { //and print what remains as well getline(in, input);
getline(in,input); if ( boost::xpressive::regex_search(input, regex) ) { //if we find a match
cout << input << endl; cout << input << endl; //start printing to std out
} while(in) { //and print what remains as well
} getline(in,input);
} cout << input << endl;
} //end of inner while
} //end of if
} //end of outer while
} //end of else
return 0;
} }

@ -27,6 +27,6 @@
using namespace std; using namespace std;
void begin(string needle, istream &in); int begin(string needle, istream &in);
#endif #endif

@ -21,20 +21,24 @@
#include <iostream> #include <iostream>
#include <string>
#include "begin.hpp" #include "begin.hpp"
using namespace std; using namespace std;
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
int works = 1; //default return value
if( argc == 2) { //assume the argument is a regex and to read from std in if( argc == 2) { //assume the argument is a regex and to read from std in
begin(argv[1], cin); works = begin(argv[1], cin); //try the search
} else if( argc == 3) { //assume the first argument is a regex and second is a filename } else if( argc == 3) { //assume the first argument is a regex and second is a filename
ifstream in(argv[2]); ifstream in(argv[2]);
begin(argv[1], in); works = begin(argv[1], in); //try the search
} else { } else { //Wrong number of command line args
cout << "Usage: begin <regex> [filename] \n"; cout << "Usage: begin <regex> [filename] \n";
} }
return 0;
return works;
} }

Loading…
Cancel
Save