1

i have a a char array in C++ which looke like {'a','b','c',0,0,0,0}

now im wrting it to a stream and i want it to appear like "abc " with four spaces insted of the null's i'm mostly using std::stiring and i also have boost. how can i do it in C++

basicly i think im looking for something like

char hellishCString[7] = {'a','b','c',0,0,0,0}; // comes from some wired struct actually... std::string newString(hellishCString, sizeof(hellishCString)); newString.Replace(0,' '); // not real C++ ar << newString; 
2
  • Can std::string's contain embedded null characters? Another option may be to use a std::vector instead. Commented Jun 27, 2010 at 8:17
  • @dreamlax: Yes, they can. The length of the string is stored independently, so there is no need for null-termination and null characters aren't treated specially. Commented Jun 27, 2010 at 8:24

2 Answers 2

10

Use std::replace:

#include <string> #include <algorithm> #include <iostream> int main(void) { char hellishCString[7] = {'a','b','c',0,0,0,0}; // comes from some wired struct actually... std::string newString(hellishCString, sizeof hellishCString); std::replace(newString.begin(), newString.end(), '\0', ' '); std::cout << '+' << newString << '+' << std::endl; } 
Sign up to request clarification or add additional context in comments.

2 Comments

Error 7 error C2782: 'void std::replace(_FwdIt,_FwdIt,const _Ty &,const _Ty &)' : template parameter '_Ty' is ambiguous
my mistake, i tried : std::replace(groupString.begin(), groupString.end(), 0, ' '); and 0 is obviously int...
1

One more solution if you replace an array by the vector

#include <vector> #include <string> #include <algorithm> #include <iostream> char replaceZero(char n) { return (n == 0) ? ' ' : n; } int main(int argc, char** argv) { char hellish[] = {'a','b','c',0,0,0,0}; std::vector<char> hellishCString(hellish, hellish + sizeof(hellish)); std::transform(hellishCString.begin(), hellishCString.end(), hellishCString.begin(), replaceZero); std::string result(hellishCString.begin(), hellishCString.end()); std::cout << result; return 0; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.