///////////////////////////////////////////////////// // // args.cpp // // Jeff Ondich and the CS257 class // // Written communally during class to illustrate // one approach to parsing command-line arguments // in C/C++. The basic approach is: (1) set your // default behaviors, (2) scan through the arguments // to set non-default behaviors, and (3) execute // the specified behaviors. // // The program's job, such as it is, is to change // its input to upper case, sending the output // to standard out. The input can come from either // a file or standard in, and there are usage and // version flags that override the input->output // and just print suitable messages. // ///////////////////////////////////////////////////// #include #include using namespace std; void printUsageStatement( const char *progName ); void printVersionStatement( const char *progName ); void capitalize( istream& in ); int main( int argc, char *argv[] ) { // args [-u] [-v] [file] // -u flag prints usage statement // -v flag prints version info // file, or stdin if file is absent, gets printed // in all caps to stdout. // Set default behaviors. char *fileName = NULL; bool printUsage = false; bool printVersion = false; for( int k=1; k < argc; k++ ) { if( strcmp( argv[k], "-u" ) == 0 ) printUsage = true; else if( strcmp( argv[k], "-v" ) == 0 ) printVersion = true; else if( k < argc - 1 ) // Too many arguments { printUsage = true; break; } else // There's a single file specified. { fileName = argv[k]; } } if( printUsage || printVersion ) { if( printVersion ) printVersionStatement( argv[0] ); if( printUsage ) printUsageStatement( argv[0] ); exit( 1 ); } if( fileName != NULL ) { ifstream fin; fin.open( fileName ); if( !fin.is_open() ) { cerr << "Can't open file " << fileName << endl; exit( 1 ); } capitalize( fin ); } else capitalize( cin ); return 0; } void printUsageStatement( const char *progName ) { cerr << "Usage: " << progName << " [-u] [-v] [file]" << endl; } void printVersionStatement( const char *progName ) { cerr << "Version: " << progName << " -0.1" << endl; } void capitalize( istream& in ) { char ch; while( in.get( ch ) ) { ch = toupper( ch ); cout << ch; } }