Conversion from string to char - c++

68,765

Solution 1

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.

Solution 2

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

char c = value[0];
Share:
68,765
ModdedLife
Author by

ModdedLife

I'm a student at the University of Kentucky pursuing a Computer Science degree. I'm told that I have a brilliant mind, but I don't always have the knowledge for implementing my ideas. I'm a visual learner and learn by example. I developed a passion creating things out of nothing at a young age. I began teaching myself web design in the fourth grade. I continued to develop my web design skills through middle school before venturing from HTML. I taught myself basic PHP programming, which influenced me to take a CS class in high school. I fell in love with the idea of programming and decided to pursue a CS career. I struggle with certain areas in programming, but still use PHP and web design as a form of relaxation. I've make countless websites and love implementing things I haven't done before.

Updated on July 24, 2022

Comments

  • ModdedLife
    ModdedLife almost 2 years

    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!

  • ModdedLife
    ModdedLife over 11 years
    Yessssss!!! Thank you! Haha Idk why I didn't try that to begin with. It seemed too simple.