C++ Program to Perform Calculations in Pure Strings
Last Updated :
16 Nov, 2022
Given a string of operations containing three operands for each operation "type of command", "first operand", and "second operand". Calculate all the commands given in this string format.
In other words, you will be given a pure string that will ask you to perform an operation and you have to perform it and print the result in order of the commands given.
- add - For addition (+) accepts two arguments num1 and num2. (similar with subtract (-), multiply (x), divide (/) ).
- percent - For percentage (%) with 100 accepts one argument num1 and num2 as '-1' always.
- log - For logarithm of num1 with base num2 accepts two arguments. (similar with exp (^) ).
- sqrt - For the square root of num1, accept one argument num1 and num2 as '-1' always.
- cbrt - For cube root of num1, accepts one argument num1 and num2 as '-1' always.
- All trigonometric functions - accepts one argument num1 and num2 as '-1' always.
Note: Print "inf" in case of any exception like divide by zero (0) and for functions that input one argument, add '-1' as the second.
Examples:
Input: "add 4 5"
Output: 9
Explanation: 4+5=9 which is to be printed.
Input: "subtract 7 6"
Output: 1
Explanation: 7-6=1 which is to be printed.
Input: "divide 2 0 multiply 6 6"
Output: inf 36 // in this case it will only print 36
Explanation: 2/0=infinity and 6*6=36 which is to be printed.
Input: "percent 50 -1"
Output: 0.5
Explanation: 50/100=0.5 which is to be printed.
Approach: It is a simple case of string handling where we need to extract each word and then calculate the operands output based on the 'type of operation'. It can be done by creating a series of if-else ladder of functions or using switch cases. If any function is invalid or not found in the returnOP function then return '-1'.
For example: "add 5 6" can be broken down as three strings using stringstream "add", "5", and "6". We will compare add with our library of functions and perform 5+6 after converting them to float. So if "add" is at position i then 5 and 6 would be at positions i+1 and i+2.
Follow the below steps to implement the above approach:
- Pass the string into the function processOperations.
- Extract each word from the string using stringstream class and store all these words in a vector strarr.
- Then check for every third word (3*k) to see the 'type of operation' being performed and compare it with the library of operations available in returnOP function.
- If that operation is found returnOP then return its float answer after calculation else returns '-1'.
- Calculate the output values based on the operation and return them to the original function processOperations.
All these operation results that we get from returnOP will then be pushed into a result vector of type float. The result vector will be our final answer which is to be returned after performing all operations.
C++14
#include <bits/stdc++.h>
using namespace std;
// MACROS for performing commands
#define e 2.718281828459045
#define pi 3.141592653589793
// function for comparing the type of operation
double returnOP(string& word,vector<string>&strarr,int& i)
{
double num1,num2;
// using MACROS if required
if(strarr[i+1].compare("e")==0)
num1=e;
if(strarr[i+1].compare("pi")==0)
num1=pi;
else num1=stof(strarr[i+1]);
if(strarr[i+2].compare("e")==0)
num2=e;
if(strarr[i+2].compare("pi")==0)
num2=pi;
else num2=stof(strarr[i+2]);
double degree=pi*num1/180;
// library of functions to calculate result
// after finding the 'type of operation'
if(word.compare("add")==0)
return num1+num2;
else if(word.compare("subtract")==0)
return num1-num2;
else if(word.compare("multiply")==0)
return num1*num2;
else if(word.compare("divide")==0)
return num1/num2;
else if(word.compare("percent")==0)
return (num2/num1)*100;
else if(word.compare("log")==0)
return log(num1)/log(num2);
else if(word.compare("exp")==0)
return pow(num1,num2);
else if(word.compare("sqrt")==0)
return sqrt(num1);
else if(word.compare("cbrt")==0)
return cbrt(num1);
else if(word.compare("sin")==0)
return sin(num1);
else if(word.compare("cos")==0)
return cos(num1);
else if(word.compare("tan")==0)
return tan(num1);
else if(word.compare("sec")==0)
return 1/cos(num1);
else if(word.compare("cosec")==0)
return 1/sin(num1);
else if(word.compare("cot")==0)
return 1/tan(num1);
else if(word.compare("sindeg")==0)
return sin(degree);
else if(word.compare("cosdeg")==0)
return cos(degree);
else if(word.compare("tandeg")==0)
return tan(degree);
else if(word.compare("secdeg")==0)
return 1/cos(degree);
else if(word.compare("cosecdeg")==0)
return 1/sin(degree);
else if(word.compare("cotdeg")==0)
return 1/tan(degree);
else if(word.compare("sininv")==0)
return asin(num1);
else if(word.compare("cosinv")==0)
return acos(num1);
else if(word.compare("taninv")==0)
return atan(num1);
else if(word.compare("secinv")==0)
return acos(1/num1);
else if(word.compare("cosecinv")==0)
return asin(1/num1);
else if(word.compare("cotinv")==0)
return atan(1/num1);
else if(word.compare("sininvdeg")==0)
return 180*asin(num1)/pi;
else if(word.compare("cosinvdeg")==0)
return 180*acos(num1)/pi;
else if(word.compare("taninvdeg")==0)
return 180*atan(num1)/pi;
else if(word.compare("secinvdeg")==0)
return 180*acos(1/num1)/pi;
else if(word.compare("cosecinvdeg")==0)
return 180*asin(1/num1)/pi;
else if(word.compare("cotinvdeg")==0)
return 180*atan(1/num1)/pi;
return -1;
}
// function for fetching each word from a string array of operations
// and pushing them into result after performing required operation
vector<double>processOperations(string& operations)
{
string word;
vector<string>strarr;
vector<double>result;
// stringstream class to extract
// word from string
stringstream ss(operations);
while(ss>>word)
strarr.push_back(word);
// passing each third word to returnOP
// to calculate final result of that query
for(int i=0;i<strarr.size();i+=3)
result.push_back(returnOP(strarr[i],strarr,i));
return result;
}
// driver's code
int main()
{
string operations="add 1 1 multiply -2 -1 cosecinvdeg 1.4142135624 -1 percent 100 20";
vector<double>ans=processOperations(operations);
for(auto& x:ans)
cout<<x<<endl;
return 0;
}
Output:
2 // adding of 1 and 1
2 // multiplying of -2 and -1
45 // cosecinvdeg 1.4142135624 and -1
20 // percentage of 100 and 20
Time Complexity: O(N)
Auxiliary Space: O(N), where N is the number of characters in string operations.
Similar Reads
C++ Program For String to Double Conversion
There are situations, where we need to convert textual data into numerical values for various calculations. In this article, we will learn how to convert strings to double in C++. Methods to Convert String to Double We can convert String to Double in C++ using the following methods: Using stod() Fun
3 min read
C++ Program For Double to String Conversion
Here, we will build a C++ program for double to string conversion using various methods i.e. Using to_stringUsing stringstreamUsing sprintfUsing lexical_cast We will keep the same input in all the mentioned approaches and get an output accordingly. Input: n = 456321.7651234 Output: string: 456321.76
2 min read
C++ Program For String to Long Conversion
In this article, we will learn how to convert strings to long in C++. For this conversion, there are 3 ways as follows: Using stol()Using stoul()Using atol() Let's start by discussing each of these methods in detail. Example: Input: s1 = "20" s2 = "30" Output: s1 + s2 long: 50 1. Using stol() In C++
3 min read
C++ Program to Sort String of Characters
Sorting a string means rearranging the characters of the given string in some defined order such as alphabetical order. In this article, we will learn how to sort a string by characters in C++.ExamplesInput: str = "geeksforgeeks"Output: "eeeefggkkorss"Explanation: The characters in the string are so
4 min read
C Program to Extract Characters From a String
Character extraction can be done by iterating through the string in the form of a character array. It basically means plucking out a certain amount of characters from an array or a string. Now, to take input in C we do it by using the following methods: scanf("%c",&str[i]); - Using a loopscanf("
2 min read
C++ Program to Make a Simple Calculator
A simple calculator is a device used to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. It makes arithmetic calculations easier and faster. In this article, we will learn how to code a simple calculator using C++.ExamplesInput: Enter an operator (+, -
3 min read
C/C++ Program for String Search
C/C++ Program for Naive Pattern SearchingC/C++ Program for KMP AlgorithmC/C++ Program for Rabin-Karp AlgorithmC/C++ Program for A Naive Pattern Searching QuestionC/C++ Program for Finite AutomataC/C++ Program for Efficient Construction of Finite AutomataC/C++ Program for Boyer Moore Algorithm â Bad
1 min read
C++ Program to Split a String Into a Number of Sub-Strings
Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. Almost all programming languages, provide a function split a string by some delimiter. In C++Note: The main disadvantage of strtok()
3 min read
C++ Program to Implement strpbrk() Function
strpbrk() is a string function in C++ STL that takes in two strings and finds the first occurrence of any character of string2 in string1. This function returns the pointer to the character of string2 in string1 if there is any, otherwise returns NULL. Syntax: char* strpbrk(const char *str1, const c
3 min read
C++ Program to Check String is Containing Only Digits
Prerequisite: Strings in C++ The string is the collection of characters or text in a string variable, surrounded by double quotes. One question arises How can we check string contains only digits in C++? So, to solve this query we can use the methods mentioned in the article given below: Example: "1
3 min read