-4

So I am making a calculator that takes a pointer string and does the calculation, the problem is I have to convert it to a int but any type of conversion function won't covert any characters that are not numbers, so in this case the multiplication operator. Help will be much appreciated, thanks!

char* x = "2 * 1"

int y = x

Printf("%d", y) //I want it to print "2"
XFanatic
  • 1
  • 2
  • 2
    https://en.wikipedia.org/wiki/Shunting-yard_algorithm – Iłya Bursov Feb 12 '22 at 01:36
  • The feature you are hoping for (like javascript eval) simply doesn't exists in c. You have to pull each character out at a time, determine if its a digit an operation *,-+ etc and then perform that calculation. You cant even delimit by spaces as I assume 2*1 is going to be valid input. You can use strtol which will pull digits until it hits a non digit and tell you how far it got – pm100 Feb 12 '22 at 02:40
  • this is called parsing see other questions https://stackoverflow.com/questions/11703082/parsing-math-expression-in-c – pm100 Feb 12 '22 at 02:42

1 Answers1

-1

A better way to do this is to take X as input and Y as input both as an int and then apply the math to it and all you would need to print is the result of both of them.

int x = 2;
int y = 1;
int z = x * y;
printf("%i", z);

or if you want you can use ctype.h library and make a for loop to go over each letter of the string and assign it on an array if it's a number using the isdigit function which would return if that one letter is a digit or not and if it is a digit you can assaign it a varible like int z[x] = *string-name*[i] so it would be like

char *anything = "thi2sst3ringhasnumber5";
int length = strlen(anything);
int x = 0;
for (int i = 0; i < length; i++)
{
  if (isdigit(anything[i]))
  {
    int numbers[x] = anything[i];
    x++;
  }
} 

and that would return to you an array of [2, 3, 5] as numbers[0, 1 ,2] so if you wanted to take multiply them you can do *something* = numbers[0] * numbers[1]; which is 2 * 3 and you can assign it to a variable and print it out.

Lychas
  • 173
  • 2
  • 11