ibadia
ibadia

Reputation: 919

Replacing and deleting a character from a string in c++?

This program is giving wrong output,, basically i want to remove the character specified and replace it by 'g'...For e.g: All that glitters is not gold if the user entered o then the output should be All that glitters is ngt ggld but the program is deleting all the characters from n onwards

 #include <iostream>
 using namespace std;
 int main()
 {
   string input(" ALL GLItters are not gold");
   char a;
   cin>>a;
   for(int i=0;i<input.size();i++)
   {
     if(input.at(i)==a)
     {
        input.erase(i,i+1);
        input.insert(i,"g");
     }
   }
    cout<<"\n";
   cout<<input;

 }

Upvotes: 0

Views: 44

Answers (2)

DanielKO
DanielKO

Reputation: 4517

Why not replace it directly? Replace your for loop with this:

for (char& c : input)
{
    if (c == a)
        c = 'g';
}

Live example here.

Upvotes: 1

baddger964
baddger964

Reputation: 1227

string& erase (size_t pos = 0, size_t len = npos);

The second parameter ( len ) is the Number of characters to erase. You have to put 1 not i+1 :

input.erase(i,1);

http://www.cplusplus.com/reference/string/string/erase/

Upvotes: 1

Related Questions