string error.

Jul 9, 2015 at 4:50pm
I want to read a text of more than one word and then replace the blank spaces with an underscore(_)..my program is showing error.please explain me.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string arr;
    string s2(" ");
    string s3("_");
cout<<"enter the text:";
getline(cin,arr);
cout <<"string is:"<<arr;

for(int i=0;i<arr.length();i++)
{
        if(arr.at(i)==s2.at(0))
        {
                              arr.replace(arr.at(i),s3.at(0));
        }
}
cout<<"\n\nnew string is:"<<arr;

system("pause");

}
Last edited on Jul 9, 2015 at 4:50pm
Jul 9, 2015 at 4:59pm
What kind of error? When you try to build your exe? When you run it?

What error message are you getting?

Andy
Jul 9, 2015 at 5:03pm
compilation errror.
this is the error log:
17. no matching function for call to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::replace(char&, char&)'
i am not able to understand this error.
Jul 9, 2015 at 5:10pm
Did you check the info on string::replace()??
http://www.cplusplus.com/reference/string/basic_string/replace/

It's saying there's no version of replace which can take two char parameters.

check out the replace algorithm!
http://www.cplusplus.com/reference/algorithm/replace/

Andy
Last edited on Jul 9, 2015 at 5:11pm
Jul 9, 2015 at 5:51pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>

int main()
{
    std::string str ;

    std::cout << "enter a string: " ;
    std::getline( std::cin, str ) ;
    std::cout << "entered string is: '" << str << "'\n" ;

    // http://www.stroustrup.com/C++11FAQ.html#for
    for( char& c : str ) if( c == ' ' ) c  = '_' ;
    
    // or: for( char& c : str ) if( std::isspace(c) ) c  = '_' ; // <cctype>

    std::cout << "    new string is: '" << str << "'\n" ;
}

http://coliru.stacked-crooked.com/a/f27f584e365af5f0
Topic archived. No new replies allowed.