0

I'm writing a c++ calculator but I keep getting stuck on the part which changes the std::string into float variable for mathematical calculation.

I've already tried atoi and using 'var' (single-quote) but it seems to result in erratically large numbers and some variations of the code won't even compile saying "Line 13 Column 18 C:\Users\User\Desktop\calculator.cpp [Error] cannot convert 'std::string {aka std::basic_string}' to 'float' in initialization".

#include <stdio.h>
#include <math.h>
#include <iostream>
#include <string>
#include <stdlib.h>

int main()
{
    std::cout << "Input arithmetic calculation: \n";
    std::string calc;
    std::cin >> calc;
    atoi( calc.c_str() );
    float result=calc;
    std::cout << "Result = ";
    std::cout << result << '\n';
}

I expect the output to be calculated such as 10*9=90 but it ends up as 10*9 or (when adding single-quote to calc in float result=calc) 1.93708e+009.

kornkaobat
  • 93
  • 9
  • The above code will not compile. You cannot assign `std::string` to `float`, as in `float result=calc;`. You also discard the return value of `atoi()`. – Fureeish Jul 28 '19 at 09:27
  • 1
    `atoi` isn't an evaluation function, which you're looking for, it just converts numeric strings to integers. For example converting `"12"` to `12`. – frogatto Jul 28 '19 at 09:28
  • So what i need is an evaluation function to calculate the string "calc"? – kornkaobat Jul 28 '19 at 09:32
  • 1
    @kornkaobat [This post](https://stackoverflow.com/questions/9329406/evaluating-arithmetic-expressions-from-string-in-c) may help you. – frogatto Jul 28 '19 at 09:39
  • 1
    Okay, I've found tinyexpr.h header file which solves my problem. – kornkaobat Jul 28 '19 at 09:44
  • 1
    Check here: https://www.geeksforgeeks.org/expression-evaluation/ – Amit G. Jul 28 '19 at 10:13
  • @Useless No. I just want to migrate from Batch language which uses this syntax set /p cal= then on the next line set /a result=%cal% – kornkaobat Jul 28 '19 at 10:25

1 Answers1

1

[...] I keep getting stuck on the part which changes the std::string into float variable for mathematical calculation.

Because:

  1. you discard the value of atoi(). The usage would look like this: float result = atoi(calc.c_str());
  2. atoi() doesn't do what you think it does. It does not perform any mathematical evaluations. It simply converts text that can be represented as a number, to said number, i.e. float x = atoi("5"); will yield x == 5. You can't use atoi() and expect it to perform mathematical calculations. It just converts.

You would need to implement this behaviour yourself.

Fureeish
  • 12,533
  • 4
  • 32
  • 62