Reputation: 919
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
Reputation: 4517
Why not replace it directly? Replace your for
loop with this:
for (char& c : input)
{
if (c == a)
c = 'g';
}
Upvotes: 1
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