Reputation: 241
For a project I'm working on, I want to convert a letter to a number (like A = 20). So I want to be able to take "AQJD" and convert that to a number. How do I take what a user inputted and grab certain elements.
Something as simple as
char myArray [] = "AQJD"
can be grabbed like so:
myArray[0] // this will return A because A is the 0th element
but how can I get what a user inputted to do something like what's above. I tried to do this (pasted below) but it wouldn't work.
string x; //assume I included <string> already
cout << "Please input what you would like to change: " << endl;
cin >> x;
char mine [] = x;
cout << mine[2] << endl;
Is there a way to pass a variable to an array like I tried above?
Upvotes: 0
Views: 36
Reputation: 630
You may use .c_str()
method of std::string
that is quite similar:
const char *mine = x.c_str();
cout << mine[2] << endl;
Upvotes: 0
Reputation: 96810
std::string
already has an operator[]
function that returns the character at the specified position. It's exactly the same as a regular char array:
cout << x[2]; // J
Upvotes: 1