2015-10-20 89 views
2

我在C++中的程序中,所有的输入到程序具有下划线(“_”)代替空格。我试图替换所有空格('')的下划线。我试过使用std :: replace,但是我一直在收到错误,我不知道我错在哪里。c + +替换字符的所有出现在字符串

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', 
} 

这回,当我尝试编译错误:

转换,从void' to non-scalar type的std :: basic_string的,性病::分配器>”要求

+1

也许读了一些'的std :: replace'文档? – juanchopanza

+0

加一:如果你的正常语言是Java,这是forgiveable。 – Bathsheba

+0

@Bathsheba什么? Java人不知道查找文档?有趣... – juanchopanza

回答

3

std::replace作品的迭代器,所以它直接修改字符串,没有必要的返回值。使用

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

代替。

1

std::replace回报void

不能分配给voidstd::string

0

您只需要使用:

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