简体   繁体   English

C ++将char转换为const char *

[英]C++ convert char to const char*

Basically i just want to loop through a string of characters pull each one out and each one has to be of type const char* so i can pass it to a function. 基本上我只想循环遍历一个字符串拉出每个字符,每个字符必须是const char *类型,所以我可以将它传递给一个函数。 heres a example. 这是一个例子。 Thanks for your help. 谢谢你的帮助。

    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);
    }

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

theval = &thestring[i];
string sym(1, thestring[i]);
theval = sym.c_str();

It gives a null-terminated const char* for every character. 它为每个字符提供以null结尾的const char *。

Usually a const char * is pointing to a full null-terminated string, not a single character, so I question if this is really what you want to do. 通常一个const char *指向一个完整的以null结尾的字符串,而不是一个字符,所以我怀疑这是否真的是你想要做的。

If it's really what you want, the answer is easy: 如果它真的是你想要的,答案很简单:

theval = &thestring[i];

If the function is really expecting a string but you want to pass it a string of a single character, a slightly different approach is called for: 如果函数确实期望一个字符串,但是你想传递一个单个字符的字符串,那么就会调用一个稍微不同的方法:

char theval[2] = {0};
theval[0] = thestring[i];
result = func(theval);

I'm guessing that the func call is expecting a C-string as it's input. 我猜测func调用期待一个C字符串作为它的输入。 In which case you can do the following: 在这种情况下,您可以执行以下操作:

string theString = "abc123";
char tempCString[2];
string result;

tempCString[1] = '\0';

for( string::iterator it = theString.begin();
     it != theString.end(); ++it )
{
   tempCString[0] = *it;
   result = func( tempCString );
}

This will produce a small C-string (null terminated array of characters) which will be of length 1 for each iteration. 这将生成一个小的C字符串(以空字符结尾的字符数组),每次迭代的长度为1。

The for loop can be done with an index (as you wrote it) or with the iterators (as I wrote it) and it will have the same result; for循环可以用索引(就像你写的那样)或迭代器(就像我写的那样)完成,它会有相同的结果; I prefer the iterator just for consistency with the rest of the STL. 我更喜欢迭代器只是为了与STL的其余部分保持一致。

Another problem here to note (although these may just be a result of generalizing the code) is that the result will be overwritten on each iteration. 这里要注意的另一个问题(尽管这些可能只是概括代码的result )是每次迭代都会覆盖result

您可以保留该元素的地址:

theval = &thestring[i];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM