简体   繁体   中英

addition and multiplication of string in C++

I am doing my C++ homework but I cannot figure out the algorithm.

I have to make a program that operates with strings.

The strings and operators(+ and *) should be differentiated by space(' ')

and multiplication operates first than addition

+) use atoi to change string to integer

for example:

INPUT: abc + b * 4 + xy * 2 + z

OUTPUT: abcbbbbxyxyz

so far this is what I did ↓

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include<sstream>
using namespace std;

enum classify {NUMBER, STRING, OPERATION, SPACE};

int char_type(string c)
{
        if (c >= "0" && c <= "9") return NUMBER;
        else if (c == "*" || c == "+") return OPERATION;
        else if (c == " ") return SPACE;
        else return STRING;
}

int main(void)
{
        string input;
        getline(cin, input);
        istringstream token(input);
        string buffer;

        while (getline(token, buffer, ' '))
                { after I classify them using enum, how can I
                  let the computer to know "multiplication first"? }
}

I cannot figure out the algorithm.

One canonical way is to convert your infix mathematical expression into Reverse Polish notation and then evaluate it. See https://en.wikipedia.org/wiki/Shunting-yard_algorithm for full details.

Algorithm:

  • Convert the input string into tokens. The tokens are separated by spaces. For example, "abc + b * 4 + xy * 2 + z" converts into the tokens "abc", "b", " ", "4", "+", "xy", " ", "2", "+", and "z".
  • Perform multiplication operations.
    • Go through the tokens one-by-one.
    • If a token is a multiplication sign ("*"):
      • Determine whether the token before or after it is the one that is the number.
      • If the token before is the number:
        • Create a temporary string, repeatedly add the token after (the letters) to the temporary string for the number of times specified by the token before (the number).
      • If the token after is the number:
        • Create a temporary string, repeatedly add the token before (the letters) to the temporary string for the number of times specified by the token after (the number).
      • Set the token before to the temporary string.
      • Make the current token (the multiplication sign) and the next token empty tokens.
    • Remove empty tokens.
  • Perform addition operations.
    • Go through the tokens one-by-one.
    • If a token is an addition sign ("*"):
      • Concatenate the token after to the end of the token before.
      • Make the current token (the multiplication sign) and the next token empty tokens.
    • Remove empty tokens.
  • Convert the tokens back into a string.

Code:

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

typedef std::string Token;
typedef std::vector<Token> Tokens;

Tokens tokenise(std::string str)
{
    Tokens tokens;

    int startOfToken = 0;

    // Move through until you find a space (" ") and then add the token (the start of the token is the previous space) and the end is the current space
    for (int i = 0; i < str.size(); i++)
    {
        if (str.substr(i, 1) == " ")
        {
            tokens.push_back(str.substr(startOfToken, i - startOfToken));

            startOfToken = i + 1;
        }
    }

    // Add last token (there is no space after it to mark it)
    tokens.push_back(str.substr(startOfToken));

    return tokens;
}

bool containsNumber(Token token)
{
    if (token.find("0") != std::string::npos)
    {
        return true;
    }
    else if (token.find("1") != std::string::npos)
    {
        return true;
    }
    else if (token.find("2") != std::string::npos)
    {
        return true;
    }
    else if (token.find("3") != std::string::npos)
    {
        return true;
    }
    else if (token.find("4") != std::string::npos)
    {
        return true;
    }
    else if (token.find("5") != std::string::npos)
    {
        return true;
    }
    else if (token.find("6") != std::string::npos)
    {
        return true;
    }
    else if (token.find("7") != std::string::npos)
    {
        return true;
    }
    else if (token.find("8") != std::string::npos)
    {
        return true;
    }
    else if (token.find("9") != std::string::npos)
    {
        return true;
    }

    return false;
}

Tokens removeEmptyTokens(Tokens tokens)
{
    Tokens newTokens;

    for (int i = 0; i < tokens.size(); i++)
    {
        // Only add token to new tokens if it isn't empty
        if (tokens[i] != "")
        {
            newTokens.push_back(tokens[i]);
        }
    }

    return newTokens;
}

Tokens performMultiplicationOperations(Tokens tokens)
{
    // Iterate through the tokens
    for (int i = 0; i < tokens.size(); i++)
    {
        // If a token is a multiplication sign ("*")
        if (tokens[i] == "*")
        {
            // Store token before sign and after sign
            std::string* previousToken = &tokens[i - 1];
            std::string* nextToken = &tokens[i + 1];

            // Find out whether the previous token or the next token is a number
            bool tokenThatIsNumber = containsNumber(*nextToken); // False if previous token is a number, true if next token is a number

            // If previous token is a number:
            if (tokenThatIsNumber == false)
            {
                // Convert previous token to a number
                int previousTokenAsInteger = std::stoi(*previousToken);

                // Temp variable to store final string
                std::string tempString;

                // Add next token to temp string as many times as previous token specifies
                for (int j = 0; j < previousTokenAsInteger; j++)
                {
                    tempString += *nextToken;
                }

                // Set previous token to temp string
                *previousToken = tempString;

                // Get rid of current token ("*") and next token
                tokens[i] = "";
                *nextToken = "";
            }
            // If next token is a number:
            else
            {
                // Convert next token to a number
                int nextTokenAsInteger = std::stoi(*nextToken);

                // Temp variable to store final string
                std::string tempString;

                // Add previous token to temp string as many times as next token specifies
                for (int j = 0; j < nextTokenAsInteger; j++)
                {
                    tempString += *previousToken;
                }

                // Set previous token to temp string
                *previousToken = tempString;

                // Make current token ("*") and next token empty
                tokens[i] = "";
                *nextToken = "";
            }
        }
    }

    // Remove empty tokens
    tokens = removeEmptyTokens(tokens);

    return tokens;
}

Tokens performAdditionOperations(Tokens tokens)
{
    // Iterate through the tokens
    for (int i = 0; i < tokens.size(); i++)
    {
        // If a token is an addition sign ("+")
        if (tokens[i] == "+")
        {
            // Store token before sign and after sign
            std::string* previousToken = &tokens[i - 1];
            std::string* nextToken = &tokens[i + 1];

            // Concatenate next token onto end of previous token
            *previousToken += *nextToken;

            // Make current token ("+") and next token empty
            tokens[i] = "";
            *nextToken = "";
        }
    }

    // Remove empty tokens
    tokens = removeEmptyTokens(tokens);

    return tokens;
}

std::string tokensToString(Tokens tokens)
{
    std::string tempString;

    for (int i = 0; i < tokens.size(); i++)
    {
        tempString += tokens[i];
    }

    return tempString;
}

int main()
{
    // Get user input
    std::string input = "";

    std::cout << "Please enter something: ";

    std::getline(std::cin, input);

    // Tokenise
    Tokens tokens = tokenise(input);

    // Perform multiplication operations
    tokens = performMultiplicationOperations(tokens);

    // Perform addition operations
    tokens = performAdditionOperations(tokens);

    // Convert tokens to strings
    std::string finalString = tokensToString(tokens);

    std::cout << finalString;
}

I am actually new to C++ so I had a hard time understanding Toggy Smith's code

But I was able to make it shorter!

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

enum classify { NUMBER, STRING };
typedef vector<string> Tokens;

Tokens tokenize(string input, string token)
{
    istringstream list(input);
    Tokens v;
    while (getline(list, token, ' '))
        v.push_back(token);
    return v;
}

int char_type(string c)
{
    if (c >= "0" && c <= "9") return NUMBER;
    else return STRING;
}

Tokens remove_empty(Tokens tokens)
{
    Tokens newTokens;
    for (int i = 0; i < tokens.size(); i++)
    {
        if (tokens[i] != "")
        {
            newTokens.push_back(tokens[i]);
        }
    }
    return newTokens;
}

Tokens multiply(Tokens tokens)
{
    for (int i = 0; i < tokens.size(); i++)
    {
        if (tokens[i] == "*")
        {
            string* left = &tokens[i - 1];
            string* right = &tokens[i + 1];
            int left_type = char_type(*left);
            int right_type = char_type(*right);

            if (left_type == NUMBER)
            {
                int number = stoi(*left);
                string tempString;
                for (int j = 0; j < number; j++)
                    tempString += *right;
                *left = tempString;
                tokens[i] = "";
                *right = "";
            }
            else if (right_type == NUMBER)
            {
                int number = stoi(*right);
                string tempString;
                for (int j = 0; j < number; j++)
                    tempString += *left;
                *left = tempString;
                tokens[i] = "";
                *right = "";
            }
        }
    }
    tokens = remove_empty(tokens);
    return tokens;
}

Tokens add(Tokens tokens)
{
    for (int i = 0; i < tokens.size(); i++)
    {
        if (tokens[i] == "+")
        {
            string* left = &tokens[i - 1];
            string* right = &tokens[i + 1];
            *left += *right;
            tokens[i] = "";
            *right = "";
        }
    }
    tokens = remove_empty(tokens);
    return tokens;
}

string tok_to_str(Tokens tokens)
{
    string tempString;
    for (int i = 0; i < tokens.size(); i++)
        tempString += tokens[i];
    return tempString;
}

int main(void)
{
    string input;
    cout << "입력 >> ";
    getline(cin, input);

    istringstream list(input);
    string token;

    // Tokenize
    Tokens tokens = tokenize(input, token);

    // Multiplication
    tokens = multiply(tokens);

    // Addition
    tokens = add(tokens);

    // Tokens to Strings
    string output = tok_to_str(tokens);

    cout << output;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM