validating user input

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

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

@ -21,20 +21,24 @@
#include <iostream>
#include <string>
#include "begin.hpp"
using namespace std;
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
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
ifstream in(argv[2]);
begin(argv[1], in);
} else {
cout << "Usage: begin <regex> [filename] \n";
works = begin(argv[1], in); //try the search
} else { //Wrong number of command line args
cout << "Usage: begin <regex> [filename] \n";
}
return 0;
return works;
}

Loading…
Cancel
Save