In Herbert Schildt's "C++ A Beginner's Guide" one of the module mastery questions is to create a program that converts lowercase letters to uppercase (and vice-versa) and displays the result without making any changes to other characters. The progam has to stop when the user enters a '.' and at the end the program has to display the number of case changes made.
It's a simple program and I got it to work just fine... maybe too fine. What I mean by this is that I got results that I wasn't expecting... seemingly good results.
First, the program as I wrote it:
When I first tested the progam I entered one character at a time and the results were what I expected. Then I thought I'd try to enter multiple characters before hitting the enter key. (For example instead of hitting just 'H' or 'f' I typed a word 'hELLO'). After hitting enter each letter in the string(?) was converted ('Hello'). The case counter accurately reflected the number of changes.Code:// C++ A Beginer's Guide - Herbert Schildt // Module 3 Mastery Check Question # 11 // Case Converter #include <iostream> using namespace std; int main() { cout << "Case Converter\n\n"; cout << "Please type something (enter a \'.\' to quit):\n\n"; char input; int caseCounter = 0; // records number of coversions while (input != '.') { cin >> input; if ((input >= 'a') && (input <= 'z')) { input = input - 32; // converts the case cout << input; caseCounter++; } else if ((input >= 'A') && (input <= 'Z')) { input = input + 32; cout << input; caseCounter++; } else cout << input; } cout << "\n\nThe number of case changes was: " << caseCounter << "\n\n"; system ("PAUSE"); return 0; }
Woo hoo! Cool! But then I got thinking:
This must mean that the loop was executing for each character typed into "input" regardles of when the enter key is hit. But I don't know how this happens. Is C++ converting the string(?) into a char array for me? And if so, is this dangerous? I mean I know that there is no bounds checking on arrays in C++... I don't want to overwrite anything important accidentally.
Or do I have it all wrong?
Any comments would be appreciated.
Thanks.