I am currently working on a program that prompts the user to input their favorite color, and then asks them to give them a position of a character within the given color. The program will then take that given number and find the character. (ie, input Yellow as the color, and the put 2 as your character. The program should then display the character at that position is "l"). I have the beginning down, when it asks you the color and character position, but am struggling to convert that given into a letter.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//------------------------------------------------------------
//begin by asking user what their favorite color is
string favColor;
cout << "Input your favorite color: ";
//store it as a variable
//------------------------------------------------------------
cin >> favColor;
//next, ask the user what character they would like to display
//------------------------------------------------------------
int displayCharacter;
cout << "Which character would you like to display: ";
//store it as another variable
//------------------------------------------------------------
cin >> displayCharacter;
//with the character saved as an int, now have program
//determine which character is in the given city
//------------------------------------------------------------
cout << "\n";
cout << "The user input: " << favColor << "\n";
cout << "The Character at position " << displayCharacter << " is: " << << endl;
>Solution :
you can use the ASCII value of the first character in the string and add the given position to it and since characters are represented as integers in ASCII, you can simply convert the integer back to a character using type casting, for example when you run the program and input Yellow as the color and 2 as the character position, it will output The character at position 2 is: l
check this out :
#include <iostream>
#include <string>
using namespace std;
int main()
{
string favColor;
cout << "Input your favorite color: ";
cin >> favColor;
int displayCharacter;
cout << "Which character would you like to display: ";
cin >> displayCharacter;
char character = favColor[displayCharacter - 1]; // -1 because array indexing starts from 0
cout << "The Character at position " << displayCharacter << " is: " << character << endl;
return 0;
}