1

Here is my code so far:

 #include "stdafx.h" #include <iostream> #include <string> using namespace std; int main() { string exp; cout << "Enter a number and raise it to a power" << endl; cin >> exp; int num = exp[0]; int pow = exp[2]; cin.get(); cin.ignore(256,'\n'); } 

Basically, I'm trying to make a program where you can enter something like "2^5" and it will solve it for you. So far, I have taken the first and third values of the string and called them "num" and "pow". (Number, Power) If you try something like "cout << num;" it will give you the decimal Ascii value. How do I convert it to a decimal?

4 Answers 4

6

You can read from cin directly to integer variables:

int n; std::cin >> n; 

but you cannot enter naturally looking expressions that way.

To read 2^5 you can use std::stringstream:

int pos = exp.find('^'); int n; std::stringstream ss; if(pos != std::npos){ ss << exp.substr(0, pos); ss >> n; } 

and similar for the second variable.

This method is implemented in Boost as boost::lexical_cast.

More complicated expressions require building a parser and I suggest, that you read more about this subject.

Sign up to request clarification or add additional context in comments.

1 Comment

or use the std::stoi() function: n = std::stoi(exp.substr(0,pos));
2

strtol is very good at this. It reads as many numeric digits as possible, returns the number, and also gives you a pointer to the character that caused it to stop (in your case that would be the '^').

1 Comment

@Alcott: atoi only gives you the first two, no error reporting whatsoever.
1
 int num; char op; int pow; if ((std::cin >> num >> op >> pow) && op == '^') { // do anything with num and pow } 

Comments

0

It seems that all your numbers are inferior to 10, in this case exp[0]-'0' and exp[1]-'0' are enough.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.