Problem replacing strings

0
Hi, I'm starting to create an interpreter of equations, I want to replace operators with words, but things are not going well ...

main.cpp

#include <string>
#include <iostream>
#include <fstream>
#include <vector>

//disables any deprecation warning
#pragma warning(disable : 4996)

//usings
using std::vector;
using std::string;
using std::cout;


string repops(string expr) {
    string iexpr = expr;
    for (int i = 0; i < iexpr.length(); i++) {

        char& c = iexpr[i];

        if (c == '+') {
            iexpr.replace(i, i, " add ");
        }
        if (c == '-') {
            iexpr.replace(i, i, " subtract ");
        }
        if (c == '*') {
            iexpr.replace(i, i, " multiply ");
        }
        if (c == '/') {
            iexpr.replace(i, i, " divide ");
        }
    }
    return iexpr;
}

int main() {
    cout << repops("1+2-1");
    std::cin.get();
    return 0;
}

I have an output like this:

1 add 2 subtract

But I wanted one like that:

1 add 2 subtract 1
    
asked by anonymous 19.06.2018 / 04:19

2 answers

0

This is a silly mistake. The second parameter of replace is the number of characters you want to replace, which in all cases should be 1 instead of i . By doing this little fix in all 4 operations, your code works as expected. See here working on ideone.

    
19.06.2018 / 04:35
0

You can implement a function that can replace all occurrences within a string, see:

#include <string>

using namespace std;

void substituir( string& str, const string& de, const string& para )
{
    size_t pos = 0;

    if( de.empty() )
        return;

    while( (pos = str.find(de, pos)) != string::npos )
    {
        str.replace( pos, de.length(), para );
        pos += para.length();
    }
}

Testing:

#include <string>
#include <iostream>

using namespace std;

void substituir( string& str, const string& de, const string& para )
{
    size_t pos = 0;

    if( de.empty() )
        return;

    while( (pos = str.find(de, pos)) != string::npos )
    {
        str.replace( pos, de.length(), para );
        pos += para.length();
    }
}

string repops( string expr )
{
    string iexpr = expr;

    substituir( iexpr, "+", " add " );
    substituir( iexpr, "-", " subtract " );
    substituir( iexpr, "*", " multiply " );
    substituir( iexpr, "/", " divide " );

    return iexpr;
}

int main( void )
{
    cout << repops( "1+2-1" ) << endl;
    cout << repops( "5*2/1" ) << endl;
    cout << repops( "7+2-1*4/8" ) << endl;

    return 0;
}

Output:

1 add 2 subtract 1
5 multiply 2 divide 1
7 add 2 subtract 1 multiply 4 divide 8
    
19.06.2018 / 15:41