From 52584c266ac00fda89b9569fac6cc53da89f1682 Mon Sep 17 00:00:00 2001 From: Micke Nordin Date: Tue, 27 Dec 2011 02:54:20 +0100 Subject: [PATCH] validating user input --- begin.cxx | 30 +++++++++++++++++------------- begin.hpp | 2 +- main.cxx | 14 +++++++++----- 3 files changed, 27 insertions(+), 19 deletions(-) diff --git a/begin.cxx b/begin.cxx index f3b0aa0..77f65d2 100644 --- a/begin.cxx +++ b/begin.cxx @@ -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; } diff --git a/begin.hpp b/begin.hpp index f6f4809..bf5c284 100644 --- a/begin.hpp +++ b/begin.hpp @@ -27,6 +27,6 @@ using namespace std; -void begin(string needle, istream &in); +int begin(string needle, istream &in); #endif diff --git a/main.cxx b/main.cxx index cfbedce..8185034 100644 --- a/main.cxx +++ b/main.cxx @@ -21,20 +21,24 @@ #include +#include #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 [filename] \n"; + works = begin(argv[1], in); //try the search + } else { //Wrong number of command line args + cout << "Usage: begin [filename] \n"; } - return 0; + + return works; + }