# Split calculation string into parts

Our professor has given us the following task (its part of a bigger document full of tasks):

Write a function in C that handles strings like "233+343" and parse them into the variables "iNum1", "cOp" and "iNum2". (I tried to translate it into english).

We mostly program in Java and my C knowledge consists of mostly provisional half knowledge.

But is my program beautiful enough to show it to a professor?

#include <stdio.h>
#include <string.h>

#define ASCII_POS_OF_0 0x30
#define ASCII_POS_OF_9 0x39

void parse_calc_string(char string[])
{

// get first number
int iNum1 = 0;
int index = 0;
char current_char = string[index];
while (current_char >= ASCII_POS_OF_0 && current_char <= ASCII_POS_OF_9)
{
iNum1 *= 10;
iNum1 += (int)current_char - ASCII_POS_OF_0;
current_char = string[++index];
}

// get operation symbol
char cOp = current_char;
current_char = string[++index];

// get second number
int iNum2 = 0;
while (current_char >= ASCII_POS_OF_0 && current_char <= ASCII_POS_OF_9)
{
iNum2 *= 10;
iNum2 += (int)current_char - ASCII_POS_OF_0;
current_char = string[++index];
}

printf("iNum1: %i\n", iNum1);
printf("cOp  : %c\n", cOp);
printf("iNum2: %i\n", iNum2);
printf("\n");
}

int main()
{
parse_calc_string("219+43");
parse_calc_string("195-143");
parse_calc_string("15*13");
parse_calc_string("212/14");
}


You can get the value for ASCII_POS_OF_0 easily by using '0'.

Your code doesn't deal with malformed strings well.

If the string is only "123" it will attempt to read beyond the contents of the string. You can fix this by checking for '\0' at the correct places.

It also doesn't handle any type of whitespace in the string at all.

• Exception handling and handling whitespace was not included in the task. Also it would bloat up this little task. – Dexter Thorn May 9 at 12:37

it is a poor programming practice to include header files those contents are not used.

I.E. in the posted code, the contents of the header file: string.h are not being used. Suggest removing the statement:

#include <string.h>

• I think this could be a comment – Dexter Thorn May 10 at 20:34
• @DexterThorn, in CodeReview, there isn't supposed to be any comments. Just answers – user3629249 May 10 at 20:45