Is there a string conversion function to char type?

Jan 26, 2019 at 10:06am
Hello, I want to ask about a question that bothers me for quite a while.
In C#, there are functions that convert string to other variables such as Convert.ToInt32() and Convert.ToDouble() which in C++ is std::stoi() and std::stod(). In C# there is also Convert.ToChar() which convert a string which has only 1 character into char type but i couldn't find this function in C++.
I think i have searched through the internet quite alot but I only can find complicated method which converts string variable into Array of characters which isn't right. Any suggestion or function that I can convert a sting of one character into a char type? Thanks in advance
Jan 26, 2019 at 10:10am
char c = mystring[0];
Jan 26, 2019 at 10:19am
Thank you very much. I never thought of string can be used with indexing operations too!
Jan 26, 2019 at 10:44am
string is nothing but an array of characters just like char array[3] = "hi"; is

When you write mystring[0] you get a character, because string is an array of characters. So there's no need to 'convert' a string to a char array to get its characters.

Anything you can do with char arrays can be done with strings. Strings are preferred because they are dynamic in size unlike char arrays whose size must be given beforehand and because of the various methods that come with strings.
Jan 26, 2019 at 4:50pm
Anything you can do with char arrays can be done with strings.

Almost. I don't think you can mess with the zero char or inject one of them into a string class as carelessly as you can C strings.
Jan 26, 2019 at 5:14pm
Are you talking about how c strings are null terminated?
Last edited on Jan 26, 2019 at 5:19pm
Jan 27, 2019 at 11:06am
Thank you Grime and jonnin for the detailed explaination regarding this topic.
I now know that
string str = "B"
is actually
char str = "B\0"
and
char str[2] = "B\0"
can be assigned to a string variable directly. My questions originates when i stumble upon Convert.ToChar in C#, but now its all good. Thanks again and I really appreciate your help!
Topic archived. No new replies allowed.