I would suggest storing the values in an array or a vector. Then, instead of using a,b,c etc, use numbers, which then can be used as an index.
Example using an array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int main()
{
constint MAX_FRUITS = 3; // Length of array
string fruits[MAX_FRUITS]; // An array of strings, size 3
int input = -1; // This will store user input
fruits[0] = "Strawberry"; // Remember, counting starts at zero
fruits[1] = "Banana";
fruits[2] = "Lemon";
while (input < 1 || input > 3) // Make sure valid number is entered
{
cout << "Please enter a number (1-3):";
cin >> input;
}
cout << "Your fruit is a " << fruits[input-1] << ".\n";
return 0;
}
I guess you could also do it using pointers but, to be honest, it'd probably get a little messy and could easily get out of hand. I'd stick with one of the two ways above.
Thanks for your suggestion, on my way home I realised someone would probably write this and should explain further
my current code is already like this:
string b [2] = {"L","R"};
string c [3] = {"L","R","H"};
string d [2] = {"R","N"};
//layout like this simply for the sake of being easy to read
I want to type in 'b', and then using rand(), it will pick one of the letters from the array to print, so using numbers wouldn't really work. (also planning on using the array numbers to pick a random letter)
If the reason matters, these are consonant blends so my aim is to make it so when you type in the letter 'b', it will randomly choose between 'l' and 'r' to print which is why i liked it in the above layout so I could read it easier :P
You don't need to define strings like that: string b [2] = {"L","R"}, quicker is string b = "LR". You can still use the [], or str.at(), to treat the string like a character array.
Characters are numbers. As an example:
1 2 3 4 5 6 7 8 9
int arr[256];
char ch;
// assume arr[] is populated
cout << "What do you want: ";
cin >> ch;
cout << arr[ch];
This works just fine, though you would have to do some math to make it make any sense.
I don't know the entire context of your program, but I think I would make a large if/elseif/else statement. Along with that I would make a function that, given a string, will return a random member of that string. Something like:
1 2 3 4 5 6 7
char ch, rand;
cout << "What do you want: ";
cin >> ch;
if (ch == 'a')
rand = getRand("LRH"); // a function you will make
elseif ....
I think this will be better in the long run, because it will be quick to add or remove options without having to worry about making new variables. It will also be easier to deal with user input error. Just a thought.