I'm trying to make a basic calculator in Visual studio where the user enters an equation and the equation is solved by taking the equation as a string and then modifying the string to give the solved equation.But when I put the equation I get the error when debugging:
Unhandled exception at 0x00007FF9A1411F28 in ConsoleApplication1.exe: Microsoft C++ exception: std::invalid_argument at memory location 0x000000195B4FF680.
Here's the code:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
void Calculation_div(string &str);
int main()
{
string a;
cin >> a;
Calculation_div(a);
cout << a;
}
void Calculation_div(string &str)
{
std::size_t div_a;
std::size_t div_r, div_l;
while(str.find('/')) {
div_a = str.find('/');
if (str.find('/', div_a + 1)) {
div_r = str.find('/', div_a + 1);
}
else {
div_r = str.length();
}
if (str.rfind('/', div_a - 1) ) {
div_l = str.rfind('/', div_a - 1) ;
}
else {
div_l = 0;
}
string bi_l = str.substr(div_l, (div_a - div_l));
string bi_r = str.substr(div_a+1, (div_r - div_a+1));
int in_l = stoi(bi_l);
int in_r = stoi(bi_r);
int res_i = in_l + in_r;
string res_s = std::to_string(res_i);
str.replace(div_l, res_s.length(), res_s);
}
}
Sorry, Rookie mistake. Turns out i just assumed string.find would return a false value instead of string::npos.I edited the code so that it runs perfectly without any errors this time around
The Edits Include:
1.Added checks for string::nops in line 20,22,28.
2.Changed length of string to replace with as div_l instead of res_s.length() in line 40
Now,
taking an input =24/2/2
Output=6