// sample code to count vowels in input // // Compile: // g++ -std=c++14 -Wall countvowels.cpp // Usage: // a.exe file // or // a.exe < file #include #include #include // for tolower using namespace std; // uses command-line arguments to set input; will read from standard input // if no command-line argument is specified // Precondition: called once void set_input(int argc, char *argv[]) { static bool called = false; if ( called ) { cerr << "set_input cannot be called twice." << endl; exit(1); } called = true; static ifstream alternative_input; // used if have filename on command line if (argc > 0 && argv[1] != nullptr && argv[1][0] != 0) { alternative_input.open(argv[1]); if (!alternative_input) { cerr << "Could not open " << argv[1] << " for input." << endl; exit(1); } // this magic sets the read buffer for cin to the read buffer for // the input stream (redirecting input from the named file) cin.rdbuf(alternative_input.rdbuf()); cerr << "Reading from " << argv[1] << endl; } } int main(int argc, char *argv[]) { set_input(argc, argv); // read characters from input, counting vowels int vowels = 0; char ch; cin >> ch; while ( cin ) { ch = tolower(ch); if ( ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ) vowels++; cin >> ch; } cout << "Number of vowels in input: " << vowels << endl; return 0; }