Argh, please use [
code] tags. And don't shout.
Here is your program again, mostly repaired. Commentary follows below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <limits>
using namespace std;
int main ()
{
//Declare all variables
int totalSales = 0;
char doAgain = 'Y';
string cityArray[8] = {"ATLANTA","BUFFALO","CHICAGO","DALLAS","FORT WORTH","LOS ANGELES","MIAMI","NEW YORK"};
int salesAmount[8] = {0};
string cityName = "";
bool cityFound = false;
int money = 0;
while (doAgain == 'Y')
{
cout << "City Name: ";
getline( cin, cityName );
transform(cityName.begin(), cityName.end(), cityName.begin(), ptr_fun <int,int> (toupper) );
cityFound = false;
for (int i = 0; i < 8; i++)
{
if (cityArray[i] == cityName)
{
cityFound = true;
// get amount from user
cout << "Enter sale amount: $";
money = 0;
cin >> money;
cin.clear();
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );
salesAmount[i] += money;
}
}
if (cityFound == false)
{
cout << "City " + cityName + " not found in list." << endl;
cout << "Do you want to search again: ";
cin >> doAgain;
cin.clear();
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );
doAgain = toupper(doAgain);
// Prompt try again
}//End if
}//End while
// Cout for loop.
for ( int i = 0; i < 8; i++)
{
cout << "Your City is: " << cityArray[i] << " and: " << salesAmount[i] << endl;
}
return 0;
}
| |
Lines 4 and 24
Alas, you cannot use
toupper() directly with
transform() because it is an overloaded function. So you must be careful to get an explicit pointer to the version of
toupper() that you want. Do this using the <functional> classes, as indicated.
Line 23
Please use
getline() with user input. The user
always (and I cannot stress this enough -- but
always) expects to deliver input (in this kind of application) by typing in his answer and finishing by pressing the
Enter key. Your input methodology needs to match the user's expectations.
Remember, users only enter text. Get text from them, not
ints or
floats or whatever. Get the text, then transform it into the
int or
float or whatever.
Lines 5, 37, and 48
That said, however, there is a slightly different way of dealing with it: use the stream scanning as you were, then clear input to where the user pressed
Enter. This resynchronizes the input stream to the same as if you had read a line of text directly.
Lines 34 - 37 and 46 - 48
There are caveats though -- since it is now possible for the user to give bad input (and set one of the fail bits) you must account it. What I have done is just minimal to prevent the program from crashing or looping forever on bad inputs. You should take more care to recognize bad inputs and bother the user for a correct one.
Well, I think I got every point. Hope this helps.