metalec
metalec

Reputation: 11

c++ calculator atof no errors but it crashes in the middle line (52)

im new at c++ and i wanted to make a simple calculator , starts crashing when you gvet to line 52 aprox. but i got stucked at converting string to integer ( i used atof) but it doesent want to work
any explenations & fixes are welcome thanks P.S. i am new to c++ if you recomend any books or sites to learn i would be happy

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main()
{
float num1;
float num2;
float sum;
string operacija;
char *x;



cout << " enter first num"<< endl;
cin >>num1;
a:
cout << " enter operator"<<endl;
cin >> operacija;
l:
cout << "enter num 2"<<endl;
cin >> num2;




if (operacija=="+"){
    sum = num1 + num2;
}
else if (operacija=="-"){

sum = num1 - num2 ;

}

else if (operacija == "/"){
    sum= num1/num2;
}
else if (operacija=="*"){
sum=num1*num2;
}





cout << sum<< endl;

cin >> x;

if ((x=="+")||(x=="-")||(x=="/")||(x=="*"))
{
    num1 = sum;
    operacija =x;

    goto l;

}




else  {


float f = atof(x);
    num1 =f;
    goto a;

   }


 return 0;
}

Upvotes: 0

Views: 397

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283733

This is bad:

char* x;
cin >> x;

What happens is that cin reads a string and stores it in the buffer identified by x. But x is uninitialized, it doesn't point anywhere in particular and certainly not to a writable buffer.

All of your x == '*' tests are broken too.

What you should do instead is first try to read a number using iostreams, and if that fails, read a string instead.

if (!(cin >> f)) {
    cin.clear();
    cin >> operacija;
}

Upvotes: 1

Related Questions