Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing chars in std::stringstream inline

I'm wondering if I can use std::replace to replace the double quotes in a stringstream with single quotes.

I have:

std::replace(
    std::ostreambuf_iterator<char>(ssScript),
    std::ostreambuf_iterator<char>(),
    '"', '\''
);

But of course ostreambuf_iterator has no default constructor, so this won't compile.

Is there another way to replace occurrences of a char in a stringstream inline like this?

like image 1000
stack user Avatar asked Apr 26 '17 07:04

stack user


Video Answer


1 Answers

The std::stringstream class provides an interface for manipulating the stream, not its content. To manipulate the content of the stream you'd have to get the string, manipulate it and then put the string in the stream like this:

#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>

int main(void)
{
    std::stringstream ss;
    ss << "\"this is a string in a stream\"";
    std::cout << "Before: " << ss.str() << std::endl;
    std::string s = ss.str();
    std::replace(s.begin(), s.end(), '"', '\'');
    ss.str(s);
    std::cout << "After: " << ss.str() << std::endl;
    return 0;
}

And you get:

Before: "this is a string in a stream"
After: 'this is a string in a stream'

like image 174
Rogus Avatar answered Nov 14 '22 22:11

Rogus