Mikkey Mikkey - 1 month ago 10
C++ Question

Converting string into char

I've got a problem with converting types in C++. I've got an expression:

string wholeExpression = "44*2";
and I want to separate numbers from operators.
If it is a operator, I use this part of code:

string subExpression;
char skladnik;

subExpression = wholeExpression.substr(poczatek, lenght);
skladnik = subExpression[0];


if it is a number:

subExpression = wholeExpression.substr(poczatek, lenght);
skladnik = atoi(subExpression.c_str());


@EDIT

switch (skladnik)
{


case '+':
case '-':
{

while (topOfStack > 0 && stack[topOfStack - 1] != '(')
{
outPut += stack[topOfStack - 1] + przecinek;
stack.resize(topOfStack - 1);
topOfStack--;
}
stack += skladnik;
topOfStack++;
break;
}

case '/':
case '*':
{
while (topOfStack > 0 && (stack[topOfStack - 1] == '*' || stack[topOfStack - 1] == '/'))
{
outPut += stack[topOfStack - 1] + przecinek;
stack.resize(topOfStack - 1);
topOfStack--;
}
stack += skladnik;
topOfStack++;
break;
}

case '(':
{
stack += skladnik;
topOfStack++;
break;
}
case ')':
{
while (stack[topOfStack - 1] != '(')
{
outPut += stack[topOfStack - 1] + przecinek;
stack.resize(topOfStack - 1);
topOfStack--;
}
if (stack[topOfStack - 1] == '(')
{
stack.resize(topOfStack - 1);
topOfStack--;
}
break;
}

default:
{
outPut += to_string(skladnik) + przecinek;
break;
}
}


}


But suddenly I've got problem with a numbers from 40 to 43 and 45 and 47 -> which are operators (in ASCII code). They are probably interpret by the switch not as numbers but as oparators. Another numbers work perfectly. How can i solve this problem?

Answer

You are using your variable skladnik in two different ways. In one code path it refers to a decoded integer, in the second code path it refers to a character. Once you've conflated the meaning like this, there's no way to tell once you're at the switch which meaning it has.

You should use two different variables, one for decoded numbers and one for operator characters. Then there will be no confusion.