#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
usingnamespace std;
string random [] = {"one", "two", "three","four","five","six","seven","eight","nine","ten"};
int number;
int main ()
{
srand(time(0));
int rand_index = rand() % 10;
cout << random[rand_index];
return 0;
}
My question is how to do this:
I want to assign one,three, five, seven, and nine =odd.
And also two, four ,six , eight , ten = even.
So that if the program asks ex. "six", then if I replied "even", the program will also respond "That is correct".
The main problem is how to assign a value to each strings.
I wouldn't list all of the numbers in an if then or statement, I like the lazy approach myself
EXAMPLE:
1 2 3 4 5 6 7 8 9 10 11 12
if(strcmp(toupper(input), "EVEN")
{
if(rand_index%2==0)
{cout << "\nThat's wrong\n";} // End of Inner IF
else
{ cout << "\nThat's right!\n";} // End of Inner ELSE
} // End of Outer IF
//... CODE CODE CODE
Or something like this, I didn't bother compiling it so there may be a few issues with what I wrote but this was more of an effort to show you the concept then to give you the code.
Is there some limitation to this function that should be pointed out?
EDIT: Also is there a reason that you didn't use toupper() on the input variable? or was that just an oversight? I ask because I'm beggining to notice a lot of the functions that I like to use have limitations on them that are not so obvious.
@computergeek - I think that it is a terminology error. strcmp is for c-string not std::string. To compare std::string with that you have to use the .c_str() function. However there are overloaded comparison operators specifically for combinations of std::string / c-string. Athar was correct in pointing out that the earlier use of strcmp was incorrect in that particular form. You can't use a std::string directly as one of the arguments. You have to use the string::c_str function. That being said - why bother when you have the more intuitive set of operators that are overloaded for this purpose?
Array indexes are zero based, not one based so I am not sure where you guys are going with this even/odd thing. Also I am unsure of why you need to work with strings. You could accomplish such a toy program easily with integral numbers. It sounds like the OP wants to quiz the user about a number being even or odd. It would be much easier to do this with integral values rather than strings. In that case you don't even need an array. Just generate a random integral value and send it to the output stream and ask the user the question. The only thing that you might need a string for is the input value that holds the answer and the value that holds the expected answer. After generating the value you can easily determine whether it is even or odd and then store the expected answer into a string that you use to compare against the user input.