tags:

views:

106

answers:

2

Hello

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;
+10  A: 

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;
}
Philipp
Hellfrost
my mistake, i tried :std::replace(groupString.begin(), groupString.end(), 0, ' ');and 0 is obviously int...
Hellfrost
+1  A: 

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