从字符串到字符的转换 - C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14825530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:43:22  来源:igfitidea点击:

Conversion from string to char - c++

c++stringcharstring-conversion

提问by ModdedLife

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?

对于我根据规范编写的程序,将变量作为字符串传递给函数。我需要将该字符串设置为 char 变量以设置另一个变量。我该怎么做呢?

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!

感谢您在高级方面的帮助!

回答by paxdiablo

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

您可以通过索引字符串从字符串中获取特定字符。例如,的第五个字符strstr[4](由于第一个字符是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.

c_str(),正如您在评论中所言,为您提供了一个char*表示(整个字符串作为 C“字符串”,更准确地说是指向第一个字符的指针)而不是char.

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

你可以同样地索引它,但在这种特殊情况下没有意义。

回答by Luis Tellez

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

您只需要使用 value[0] 并返回第一个字符。

char c = value[0];