Evaluate an array expression with numbers , + and | C ++ program to find sum of given array of string type in integer form ; Function to find the sum of given array ; if string is empty ; stoi function to convert string into integer ; stoi function to convert string into integer ; Find operator ; If operator is equal to ' + ' , add value in sum variable else subtract ; Driver Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateSum ( string arr [ ] , int n ) { if ( n == 0 ) return 0 ; string s = arr [ 0 ] ; int value = stoi ( s ) ; int sum = value ; for ( int i = 2 ; i < n ; i = i + 2 ) { s = arr [ i ] ; int value = stoi ( s ) ; char operation = arr [ i - 1 ] [ 0 ] ; if ( operation == ' + ' ) sum += value ; else sum -= value ; } return sum ; } int main ( ) { string arr [ ] = { "3" , " + " , "4" , " - " , "7" , " + " , "13" } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << calculateSum ( arr , n ) ; return 0 ; }