My homework problem is the following :Write a program that accepts a string from the user and then replaces all occurrences of
the letter e with the letter x. I got the following code below that can recognize to find characters and where they are at but I don't know how to get it to replace and 'e' with a 'x'.

#include <iostream>
#include <string>
using namespace std;

int main()
{
	string y;
	char x;
	size_t found=0;
	size_t ind=0;


	cout<<"Please enter a string: "<<endl;
	cin>>y;
	cout<<"Please enter a character: "<<endl;
	cin>>x;

	while(found!=-1)
	{
	found=y.find(x,ind);
	ind=found+1;
	
	if(found==-1)
	{break;}

	cout<<"Character is found at "<<(int) found<<"\n";}

	cin.get();
	cin.get();
return 0;
}
while(found!=-1)
	{
	found=y.find(x,ind);
	ind=found+1;
	
	if(found==-1)
	{break;}

The above can be better written like this because it doesn't require so much code and if statements.

while( (fund = y.find(x,ind)) != string::npos )
{
       ind=found+1;
    // etc etc
}
while(found!=-1)
	{
	found=y.find(x,ind);
	ind=found+1;
	
	if(found==-1)
	{break;}

The above can be better written like this because it doesn't require so much code and if statements.

while( (fund = y.find(x,ind)) != string::npos )
{
       ind=found+1;
    // etc etc
}

I'm not sure what the "string::npos" does and I'm still not sure how to have a string of characters and replace 'e' with 'x'

string::npos is what the std::string.find() method returns when the search string is not found. Read about it in the documentation for the string class.

replace() will replace one instance of a character or string of characters with another. However, for a single character its just as easy to replace the character yourself. y[found] = 'x';

Why do you have to do something that complicated??

Here is what I came up with!

#include <iostream>
#include <string>
using namespace std;

int main()
{
	string y;
	char x;

	cout<<"Please enter a string: "<<endl;
	cin>>y;
	cout<<"Please enter a character: "<<endl;
	cin>>x;

	cout << endl << endl << endl;

	for(int i = 0; i < y.length(); i++)
	{
		if(y[i] == x)
		{
			cout << x << " found at " << i << '.' << endl;

			cout << "Replacing the " << y[i] << " with 'x'." << endl << endl << endl;
			y[i] = 'x';
		}
	}

	cout << "The final string is " << endl << y << endl;

	return 0;
}
commented: good simple solution :) +36

Oh thanks a lot that's much easier to understand. I was trying to do that y thing but someone told me it was wrong.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.