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;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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++:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.

1
2
3
4
5
Initialize variables
Get input
    If middle input is a valid operand (+, -, /, *) perform the operation
    Display output
    Wait for another input


EDIT: ah, somebody posted already.
Last edited on
Would

cin >> r >> s >> l

Capture all of say "25/100" with the use only pressing enter after 100? The goal of this is to have the user only press enter once. Not having to enter '25' then '/' then '100' but just a one time entry by the user.
Yes it should capture all those variables, you can also try it and see for yourself
Topic archived. No new replies allowed.