Reputation: 8099
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;
Upvotes: 1
Views: 753
Reputation: 551
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;
}
Upvotes: 1
Reputation: 49802
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;
}
Upvotes: 10