0

I'm pretty new to C++ and am working on a simple function to convert letters to integers (L to 1, O to 0, B to 8) but keep getting a result that's just a "1". The cout is still just "1" in the function body so I'm wondering if I'm misunderstanding str.replace();? Is there a way to change multiple characters without it being super bulky?Here's my source code below. Thanks in advance

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

string encodeString(string str){
    
    
    for(int i=0;i<str.size();i++){
            toupper(str[i]);
            
            str.replace(str.begin(),str.end(),"O",'0');
            str.replace(str.begin(),str.end(),"L",'1');
            str.replace(str.begin(),str.end(),"B",'8');
            //converts index to uppercase and replaces with integer value if L, O, B
        
    } 
    cout<<str;
    return str;
}


int main() {
    
    string str;
    cout<<"Enter your string: "<<endl;
    getline(cin,str);
    cout<<"Your encoded string : "<<encodeString(str);
    

}
AstralV
  • 119
  • 7
  • 2
    " and ' mean different things. – 273K Feb 10 '22 at 21:02
  • 1
    The line `toupper(str[i]);` returns the upper case character for the parameter passed in but you are not using the return value so actually it doesn't do anything. – Jerry Jeremiah Feb 10 '22 at 21:04
  • `toupper(str[i]);` doesn't directly do anything. `toupper` doesn't modify its argument in place, it returns a new value. You also don't need to call `replace` over and over again in your loop. – Nathan Pierson Feb 10 '22 at 21:04
  • 2
    ...But also take a look at what [replace](https://en.cppreference.com/w/cpp/string/basic_string/replace) actually does. You're invoking overload (4), I believe, which has a very different effect than you want. – Nathan Pierson Feb 10 '22 at 21:07
  • oh ok, so I should be using str[i]=toupper(str[i])? I can probably omit changing character cases at all is there an alternative to str.replace()? could I just use if loops to replace them? hmm – AstralV Feb 10 '22 at 21:12
  • 1
    @Foxsea Yes. Always helps to [read documentation](https://en.cppreference.com/w/cpp/string/byte/toupper) on where a function comes from (the header, which in this case is `` and you're not including that; also a mistake), what it does, and how to use it. – WhozCraig Feb 10 '22 at 21:15
  • _" is there an alternative to str.replace()?"_ [How to replace all occurrences of a character in string?](https://stackoverflow.com/questions/2896600/how-to-replace-all-occurrences-of-a-character-in-string) – Drew Dormann Feb 10 '22 at 21:17
  • @Foxsea There are a lot of ways to do this. Another is [using `std::transform`](https://godbolt.org/z/99PG97hPY) – WhozCraig Feb 10 '22 at 21:29

0 Answers0