Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstring>
- int numDigits(int number)
- {
- int digits = 0;
- while (number) {
- number /= 10;
- digits++;
- }
- return digits;
- }
- int isValidExpr(char* expr) {
- if (strcmp(expr, "zero") == 0)
- return 0;
- else if (strcmp(expr, "one") == 0)
- return 1;
- else if (strcmp(expr, "two") == 0)
- return 2;
- else if (strcmp(expr, "three") == 0)
- return 3;
- else if (strcmp(expr, "four") == 0)
- return 4;
- else if (strcmp(expr, "five") == 0)
- return 5;
- else if (strcmp(expr, "six") == 0)
- return 6;
- else if (strcmp(expr, "seven") == 0)
- return 7;
- else if (strcmp(expr, "eight") == 0)
- return 8;
- else if (strcmp(expr, "nine") == 0)
- return 9;
- else if (strcmp(expr, "plus") == 0)
- return 10;
- else if (strcmp(expr, "minus") == 0)
- return 11;
- else
- return -1;
- }
- void calculateExpression(char* expr) {
- int result = 0;
- int i = 0;
- int j = 0;
- char substr[1024];
- bool isAtPlus = true;
- int lastExpr = 0;
- while (expr[i] != '\0')
- {
- substr[j] = expr[i];
- substr[j + 1] = '\0';
- if (isValidExpr(substr) != -1)
- {
- int expr = isValidExpr(substr);
- if (expr == 10)
- {
- if (isAtPlus)
- result += lastExpr;
- else
- result -= lastExpr;
- isAtPlus = true;
- lastExpr = 0;
- }
- else if (expr == 11)
- {
- if (isAtPlus)
- result += lastExpr;
- else
- result -= lastExpr;
- isAtPlus = false;
- lastExpr = 0;
- }
- else
- {
- lastExpr = lastExpr * 10 + expr;
- }
- j = 0;
- ++i;
- continue;
- }
- ++i;
- ++j;
- }
- if (isAtPlus)
- result += lastExpr;
- else
- result -= lastExpr;
- int number = result;
- char numberArray[124];
- bool isNegative = number < 0;
- if (isNegative)
- number *= -1;
- for (i = 0; number != 0; ++i, number /= 10)
- {
- numberArray[i] = number % 10 + '0';
- }
- numberArray[i--] = '\0';
- char resultString[124];
- if (isNegative)
- {
- resultString[0] = '-';
- j++;
- }
- while (i >= 0)
- {
- resultString[j] = numberArray[i];
- j++;
- i--;
- }
- resultString[j] = '\0';
- strcpy_s(expr, strlen(expr), resultString);
- }
- int main()
- {
- int size;
- std::cout << "Enter string's size: ";
- std::cin >> size;
- std::cout << "Enter the string: ";
- char* arr = new char[size + 1];
- std::cin >> arr;
- calculateExpression(arr);
- std::cout << arr;
- delete [] arr;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement