Problem when replacing strings

Asked

Viewed 47 times

1

Hi, I’m starting to create an equation interpreter, I want to replace the operators with words, but things aren’t 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 a way out like this:

1 add 2 subtract

But I wanted one like this:

1 add 2 subtract 1
  • 1

    You are on stackoverflow

  • 1

    Your English is bad? No Worry, because we Speak Portuguese here! Don’t post questions in English, Please!

2 answers

0

This is a silly error. The second parameter of replace is the amount of characters you want to replace, which in all cases should be 1 instead of i. Doing this small correction in the 4 operations, your code works as expected. See here working on ideone.

0

You can implement a function capable of replacing all occurrences within a string, see only:

#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;
}

Exit:

1 add 2 subtract 1
5 multiply 2 divide 1
7 add 2 subtract 1 multiply 4 divide 8

Browser other questions tagged

You are not signed in. Login or sign up in order to post.