Friday, July 31, 2009

C++ How do I find the the place within an array by using letters?

I have an array of strings and I display the content to the user out on the screen with letters instead of numbers. So a. How, b. are, c. you, d. today. Then I ask the user to enter a selection by entering a, b, c, or d. How can I figure out what position in the array the user selected without doing a linear search (one by one)?? So if the user entered c, how can I manipulate it to know it was spot 2 since the array starts from zero.





Thanks for anyones help!!

C++ How do I find the the place within an array by using letters?
Hello,


Knowing that the ASCII code for 'a' is 97, you can cast the user's input (a char) to int and decrease 97. Then, if the user has entered 'a', it will be equivalent to the number 0.


Here's an example:





string strs[30]; //or whatever


//get your strings


char answer;


//print options here


cout %26lt;%26lt; "Please enter a choice: ";


cin %26gt;%26gt; answer;


//check input correctness


cout %26lt;%26lt; "You chose: " %26lt;%26lt; strs[(int)answer-97];





HTH,


Itay


No comments:

Post a Comment