-
Reading a string
I am writing a stack program to evaluate infix expressions and I have everything done and ready to go except one hurdle I cannot seem to pass. Let's say I have a string test; now I read in 4 + 3 5 6 - * into the string. How do i operate on the string character by character so that each character can have an operation performed on it (and yes it has to have spaces between each char/int). I know it's probably an easy answer but I'm stumped. Thanks ya'll!
-
Parse the string into individual variables and perform your operations. A string is just a char array, so you can do something like this
Code:
for ( int i = 0; i < SIZE; i++ ) {
if ( isnumeric( string[i] ) ) {
num[i] = string[i];
}
else if ( isalpha( string[i] ) ) {
if ( string[i] == '+' || string[i] == '-' || string[i] == '*' || string[i] == '/' ) {
oper[i] = string[i];
else {
cout << "Error, invalid operator" << endl;
}
}
else {
cout << "Invalid input" << endl;
}
}
-
*pointers way to parse should work for integer input but it won't work for decimal input and it has trouble with parenthesis (if you are tuly using an infix expression). A more general way to parse would be to use strtok() or equivalent string class member function using space a the delimiter, assuming there is a space between each parenthesis, operand, and operator. If spaces aren't appropriately supplied, they can be put there before the parsing, but it is easier to request input to be space delimited