Output is incorrect
Aug 25, 2009 at 10:47pm UTC
I am trying to make an application that will display what color a particular item number entered by the user. The errors display correctly the part that is not working is the output if everything comes to true. I always get a display of "The color is blue" if I enter "56b89" comes out blue if I enter "67W90" comes out blue. Can someone please show me the error of my ways please. Thanks for the help.
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
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string item = "" ;
cout << "Enter your 5-digit item #: " ;
cin >> item;
transform(item.begin(), item.end(), item.begin(), toupper);
while (item.length() != 5)
{
cout << "Invalid item #. Please enter a 5-digit item # " ;
cin >> item;
transform(item.begin(), item.end(), item.begin(), toupper);
}
if (item.length() == 5)
{
if (item.find("B" , 2))
cout << "Your color is blue" << endl << endl;
else if (item.find("G" , 2))
cout << "Your color is green" << endl << endl;
else if (item.find("R" , 2))
cout << "Your color is red" << endl << endl;
else if (item.find("W" , 2))
cout << "Your color is white" << endl << endl;
}
else
cout<< "Invalid item no matching color..." ; // if code is not from any of the above.
return 0;
}
Aug 25, 2009 at 10:56pm UTC
Aug 25, 2009 at 11:12pm UTC
I am not getting the link you sent me the size_t isnt even talked about in my chapter that is showing me the find. Or am I just totally not understanding ?
Aug 26, 2009 at 12:32am UTC
No, the return value , not the return type . The return value section on that page. See what the function returns in each case.
Aug 26, 2009 at 12:40am UTC
You want to check whether item.find(x) is equal to something. Think 'no position'. It's part of the string:: class.
Aug 26, 2009 at 2:21am UTC
thanks for the hints guys i got it to work not sure if its the best way but works.
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
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string item = "" ;
cout << "Enter your 5-digit item #: " ;
cin >> item;
while (item.length() != 5)
{
cout << "Invalid item #. Please enter a 5-digit item # " ;
getline(cin, item);
}
if (item.length() == 5)
{
if ('B' == toupper(item[2]))
cout << "Your color is blue" << endl;
else if ('G' == toupper(item[2]))
cout << "Your color is green" << endl;
else if ('R' == toupper(item[2]))
cout << "Your color is red" << endl;
else if ('W' == toupper(item[2]))
cout << "Your color is white" << endl;
}
else
cout<< "Invalid item no matching color..." ; // if code is not from any of the above.
return 0;
}
Topic archived. No new replies allowed.