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

Melvin M.
  • 3,280
  • 3
  • 15
  • 23

3 Answers3

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.

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
1

std::replace returns void.

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

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
0

You just have to use :

 std::replace( j.begin(), j.end(), '_', ' ');
 cout<<j;
vishal
  • 2,258
  • 1
  • 18
  • 27