C++ 将 char 转换为 const char*
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8437099/
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
C++ convert char to const char*
提问by user1054513
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. heres a example. Thanks for your help.
基本上,我只想遍历一串字符,将每个字符拉出,并且每个字符都必须是 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);
}
回答by Luchian Grigore
You can take the address of that element:
您可以获取该元素的地址:
theval = &thestring[i];
回答by dimitri
string sym(1, thestring[i]);
theval = sym.c_str();
It gives a null-terminated const char* for every character.
它为每个字符提供一个以空字符结尾的 const char*。
回答by Mark Ransom
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.
通常 aconst char *
指向一个完整的以空字符结尾的字符串,而不是单个字符,所以我怀疑这是否真的是你想要做的。
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);
回答by Greyson
I'm guessing that the func
call is expecting a C-string as it's input. In which case you can do the following:
我猜这个func
调用需要一个 C 字符串作为输入。在这种情况下,您可以执行以下操作:
string theString = "abc123";
char tempCString[2];
string result;
tempCString[1] = '##代码##';
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; I prefer the iterator just for consistency with the rest of the STL.
该for
循环可以用指数来完成(因为你写的),或者使用迭代器(因为我写的),它会具有相同的结果; 我更喜欢迭代器只是为了与 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
每次迭代时都会被覆盖。
回答by Piyush Kumar
You can keep the address of that element:
您可以保留该元素的地址:
theval = &thestring[i];
theval = &thestring[i];