C++将char转换为const char*

use*_*513 11 c++ const char

基本上我只想循环遍历一个字符串拉出每个字符,每个字符必须是const char*类型,所以我可以将它传递给一个函数.这是一个例子.谢谢你的帮助.

    string thestring = "abc123";
    const char* theval;
    string result;

    for(i = 0; i < thestring.length(); i++){
        theval = thestring[i]; //somehow convert this must be type const char*
        result = func(theval);
    }
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 19

您可以获取该元素的地址:

theval = &thestring[i];
Run Code Online (Sandbox Code Playgroud)


dim*_*tri 15

string sym(1, thestring[i]);
theval = sym.c_str();
Run Code Online (Sandbox Code Playgroud)

它为每个字符提供以null结尾的const char*.

  • 不是你的downvoter,但这并没有回答OP实际问的问题. (2认同)
  • 这正是我需要做的 &amp;thestring[i] 给出了 abc123、bc123、c123、123、23、3 的结果。这给了我每个单独的字符,谢谢 (2认同)

Mar*_*som 5

通常,a const char *指向完整的以零结尾的字符串,而不是单个字符,因此我怀疑这是否真的是您想要的。

如果这确实是您想要的,答案很简单:

theval = &thestring[i];
Run Code Online (Sandbox Code Playgroud)

如果该函数确实需要一个字符串,但是您希望向其传递一个单个字符的字符串,则需要一种稍微不同的方法:

char theval[2] = {0};
theval[0] = thestring[i];
result = func(theval);
Run Code Online (Sandbox Code Playgroud)