3

I have a program in C++ in which all the input into the program has underscores('_') instead of spaces. I'm trying to replace all the underscores which spaces(' '). I tried using std::replace but I keep getting errors, I'm not sure where I'm getting it wrong.

int main() { string j = "This_is_a_test"; j = std::replace( j.begin(), j.end(), '_', ' '); // I'm trying to get: This is a test from 'j', } 

This is returning an error when I try compiling:

conversion from void' to non-scalar typestd::basic_string, std::allocator >' requested

5
  • 1
    Maybe read some std::replace documentation? Commented Oct 20, 2015 at 11:41
  • Plus one: this is forgiveable if your normal language is Java. Commented Oct 20, 2015 at 11:43
  • @Bathsheba What? Java people don't know to look up documentation? Interesting... Commented Oct 20, 2015 at 11:44
  • Regular expression people certainly don't. Commented Oct 20, 2015 at 11:45
  • @MelvinRufetu See the duplicate linked above. That has solutions to your problem. Commented Oct 20, 2015 at 11:47

3 Answers 3

4

std::replace works on iterators, so it modifies the string directly, without a necessary return value. Use

std::replace(j.begin(), j.end(), '_', ' '); 

instead.

Sign up to request clarification or add additional context in comments.

Comments

1

std::replace returns void.

You can't assign void to std::string.

Comments

0

You just have to use :

 std::replace( j.begin(), j.end(), '_', ' '); cout<<j; 

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.