Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion from string to char - c++

For a program I'm writing based on specifications, a variable is passed in to a function as a string. I need to set that string to a char variable in order to set another variable. How would I go about doing this?

This is it in the header file:

void setDisplayChar(char displayCharToSet);

this is the function that sets it:

void Entity::setElementData(string elementName, string value){
    if(elementName == "name"){
            setName(value);
    }
    else if(elementName == "displayChar"){
    //      char c;
      //      c = value.c_str();
            setDisplayChar('x');//cant get it to convert :(
    }
    else if(elementName == "property"){
            this->properties.push_back(value);
    }
}

Thanks for the help in advanced!

like image 832
ModdedLife Avatar asked Feb 12 '13 04:02

ModdedLife


People also ask

How to convert a string to a character with the Char?

The char.Parse () function takes a string variable as a parameter and returns a character. The following code example shows us how to convert a string to a character with the char.Parse () function in C#.

How to copy String to char array in C++?

Begin Assign a string value to a char array variable m. Define and string variable str For i = 0 to sizeof (m) Copy character by character from m to str. Print character by character from str. End We can simply call strcpy () function to copy the string to char array. Begin Assign value to string s.

How to convert a string to a char array in Java?

The ToCharArray method of the string class converts a string to a character array. The ToCharArray method of the string class converts a string to a character array. The following code snippet creates a string into a char array. string sentence = "Mahesh Chand"; char[] charArr = sentence.ToCharArray();

How to print character by character from string to char array?

Begin Assign a string value to a char array variable m. Define and string variable str For i = 0 to sizeof (m) Copy character by character from m to str. Print character by character from str. End


2 Answers

You can get a specific character from a string simply by indexing it. For example, the fifth character of str is str[4] (off by one since the first character is str[0]).

Keep in mind you'll run into problems if the string is shorter than your index thinks it is.

c_str(), as you have in your comments, gives you a char* representation (the whole string as a C "string", more correctly a pointer to the first character) rather than a char.

You could equally index that but there's no point in this particular case.

like image 77
paxdiablo Avatar answered Oct 07 '22 03:10

paxdiablo


you just need to use value[0] and that returns the first char.

char c = value[0];
like image 34
Luis Tellez Avatar answered Oct 07 '22 01:10

Luis Tellez