change a character into a number

Hello everyone I am trying to write a code that will take a word the user enters and change certain characters into numbers for example if the user enters a word containing "e" the cout will display a 3 in its place.
ex. free becomes fr33.
here is what I have but I am getting an error with the char e=3;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
            cout<<"enter a word"<<endl;
            cin>>word;
            std::string str (word);
                for (unsigned i=0; i<str.length(); ++i)
               if (str.at(i)=='e')
               {
               char e='3';
               
               cout<<word<<endl;
               
               }        

        }


thank you all!
It depends if you need to change the word or only output.
Example with changing word;
1
2
3
4
for (unsigned i=0; i<str.length(); ++i)
    if(str.at(i) == 'e')
        str.at(i) = '3';
std::cout << str << '\n';
Last edited on
the code above is changing the word but the output is the same as the user entered?
also why does it output multiple times depending on the amount of 'e's in the input word?

I am very grateful for your help MiiNiPaa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <algorithm>


int main()
{
	std::string free = "free";

	std::replace(free.begin(), free.end(), 'e', '3');

	std::cout << free << std::endl;

	std::cin.ignore();
	return 0;
}
Last edited on
Your code:
1
2
3
4
5
for (unsigned i=0; i<str.length(); ++i)
    if (str.at(i)=='e') { //if e is found...
        char e='3';  //declare ne variabl eand assign 3 to it. As we do not use this variable, this does not do anything
        cout<<word<<endl; //Output word
    }     

note that it will output word every time e is encountered as it is inside loop and conditional branch.

@Yanson I believe OP is supposed to use loops and specific member function for this assigment.
Last edited on
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string str = "free";
    
for (unsigned i=0; i < str.length(); i++) // i++ instead of ++i
    {
        if(str.at(i) == 'e')
            str.at(i) = '3';
    }
    
    cout << str << '\n';
	return 0;
}
@kemort Preincrement should be preferred to postincrement if there is no logic require otherwise. For complex types pre-increment will be faster than post-increment, and for good style training and cinsistensy it is better to use pre-version even with primitive types.
awwwwww
my cout was output the word not the string!
got it thanks a million kemort and miinipaa!
closed account (48T7M4Gy)
@MiiNiPaa
i++ or ++i is not worth arguing about. After all it's ++C we are programming in.
Topic archived. No new replies allowed.