### Converting strings to ints

How would one convert a string datatype, such as
"123+456"

My goal is to be able to have a user input a string as an equation then have my program read the first set of numbers in the string, then the mathematical symbol, then the second set of numbers and store the information. it would then read the symbol and either multiply, divide, subtract, or add the two numbers, and throw an error if any other is used, most likely using switches to determine this.

And convert it to two ints
int a = 123;
int b = 456;
 ``123456789101112131415`` ``````int main() { long r, l; char s; while (scanf("%ld%c%ld", &r, &l, &s) == 3) { switch (s) { case '+': printf("%ld + %ld = %ld\n", r, l, r+l); break; .... default: puts("Unrecognised operand\nFormat: num1 [operand] num2"); } } return 0; }``````
Last edited on
Well, that has a bit I don't understand, but I will take your word for it and try it for myself. Thank you.

Edit: Can you explain what the '%ld' is? I take it that the '%' is mod and the 'l' is the long variable l, but what is the 'd' from?

Is there a way you can also write that in psudo code?
Last edited on
The code above is written in C language. The %ld means to read a long int, %c means read char.

Equivalent c++:
 ``1234567891011121314`` ``````int main() { long r, l; char s; while (std::cin >> r >> s >> l) { switch (s) { case '+': std::cout << r << " + " << l << " = " << r + l << std::endl; break; default: std::cout << "Unrecognised operand\nFormat: num1 [operand] num2\n"; } } return 0; }``````

http://www.cplusplus.com/reference/cstdio/printf/

From what I've read, %l is the length specifier, while d is the type specifier. %ld is equivalent to signed long int. I do believe that using %l without d is not a valid specifier.

scanf takes user input then stores them as the mod indicated to the address of the variable (i.e, 123+456 would be stored as
r = 123, c = '+', l = 456.

Using a switch to determine what to do, if s is a valid operand, then it performs the operation on the two long numbers.

 ``12345`` ``````Initialize variables Get input If middle input is a valid operand (+, -, /, *) perform the operation Display output Wait for another input``````