-6

What works:

double a1;
a1 = 2+4;
std::cout << a1;

What I want it to be:

double a1;
std::cin >> a1;
std::cout << a1;

But when I type 2+4, I get the output 2, then 4, I want it to sum at once.

Edgaras
  • 1
  • 1
  • 6
    `cin` is not going to solve math for you. You need to read it in as a string, parse the equation and then solve it. – NathanOliver Apr 15 '16 at 11:47
  • @NathanOliver please don't help maintaining people confusion about equation and expression, there is nothing to "solve" here – Guiroux Apr 15 '16 at 12:00
  • @Guiroux I was giving the OP an general way to make a calculator. That can solve expressions like `2+4` or more complex things like `x^2-4=0`. I chose equation as it covers all of it. – NathanOliver Apr 15 '16 at 12:15

1 Answers1

2

C++ will not magically do the math for you, you need to parse input, check for errors and do the calculation. For simple math you can use stream operations, to make it more advances I suggest regexp, for further more advances syntax you need parser http://www.boost.org/doc/libs/1_59_0/libs/spirit/repository/example/qi/calc1_sr.cpp.

std::regex pattern("(\\d+)\\s*(\\+)\\s*(\\d+)");
std::string line;
while (std::getline(std::cin, line)) {
  std::smatch sm;
  if (std::regex_match(line, sm, pattern)) {
    int val1 = std::stoi(sm[1]);
    std::string op = sm[2];
    int val2 = std::stoi(sm[3]);
    std::cout << (val1 + val2) << "\n";
  }
}
marcinj
  • 48,511
  • 9
  • 79
  • 100
  • What does the pattern mean? – Edgaras Apr 15 '16 at 12:34
  • @Edgaras this is a variable, you need to find a good book to start with the basics, see here: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – marcinj Apr 15 '16 at 12:44