C++ convert char to const char*

后端 未结 5 1186
情歌与酒
情歌与酒 2020-12-10 03:42

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. Th

5条回答
  •  情歌与酒
    2020-12-10 04:32

    I'm guessing that the func call is expecting a C-string as it's input. 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.

    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.

    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.

提交回复
热议问题