INFO1-CE9265 November 7, 2012

Perform the input in only one place.

The mysterious expression q - p is a size_t. Call clear and ignore only when an exclamation point has detected that the istream (in this case, cin) is unhealthy. Send error messages to cerr, not to cout.

	//Ask currency code
	cout<<"Enter your currency code (EUR, GBP, KWR, USD) for Currency " << q - p + 1 <<" :";
	string code;
	cin>>code;
	//Check if the input for code is valid.
	while( (code != "USD" && code != "EUR" && code != "KWR" && code != "USD") ){
		cout <<"Invalid input. Chose EUR, GBP, KWR or USD. Try again.\n"
			<<"Enter your currency code (EUR, GBP, KWR, USD) for Currency " << q - p + 1 << " :";
		cin.clear();
		cin.ignore();
		cin>>code;
	}
	for (;;) {
		cout << "Enter your currency code (EUR, GBP, KWR, USD) for Currency " << q - p + 1 <<" :";
		string code;
		cin >> code;

		if (!cin) {
			cerr << "Could not input a string.  Try again.\n";
			cin.clear();
			//Discard everything up to and including the '\n'.
			cin.ignore(INT_MAX, '\n');
			continue;
		}

		if (code == "USD" || code == "EUR" || code == "KWR" || code == "USD") {
			break;
		}

		cerr << "Invalid input.  Choose EUR, GBP, KWR or USD. Try again.\n";
	}

Don’s store the zero into the vector.

v is a vector<int>. i is born containing garbage. If the first attempt at input fails, the first call to push_back will copy garbage into the vector. Then the comparison of i to zero in the while statement will behave unpredictably. The check for input error came too late to help us. No reason to keep i alive after the loop is over. The first comment is not true. Output a newline at the end of the program.

It’s a good thing that the container is a vector, not a list, because we can’t subtract 1 from a list iterator.

	//0 will be eliminated from the vector
	int i;		//uninitialized variable
	do		// read input until 0 or !cin
	{
		cin >> i;
		v.push_back (i);
	}
	while (i);

	if (!cin)	//check for input error
	{
		cerr <<  "Input failed";
		exit(EXIT_FAILURE);
	}
	cout << "Please enter any number of integers (enter 0 to exit):\n";

	//print out the results
	//v.size - 1 to eliminate the 0
	cout << "The vector contains " << v.size() - 1 << " numbers.\n";

	//v.end - 1 to eliminate the 0
	for (vector<int>::const_iterator it = v.begin(); it != v.end() - 1; ++it)
	{
		cout << *it << "  ";
	}

Don’t examine or use the value of i until after we have verified that the input was successful.

	for (;;) {
		int i;	//uninitialized variable
		if (!(cin >> i)) {
			cerr << "Input failed.\n";
			exit(EXIT_FAILURE);
		}

		if (i == 0) {
			break;	//Don't store the 0 into the vector.
		}

		v.push_back(i);
	}

	//Print out the results.
	cout << "The vector contains " << v.size() << " numbers.\n";

	for (vector<int>::const_iterator it = v.begin(); it != v.end(); ++it) {
		cout << *it << "  ";
	}
	cout << "\n";