0

i have an error when i run this code and I don't know what it is, I get an error in string in visual studio app

the error " Exception thrown at 0x7A45FF80 (ucrtbased.dll) in ConsoleApplication1.exe: 0xC0000005: Access violation reading location 0x00000000."

#include <iostream>
using namespace std;
#include <string>

int main()
{
    float userinput01 = 0, userinput02 = 0;
    float avareg = 0;
    string option = 0;

    cout << "Welcome to Calculator app!\n" << "What is the desired operation?\n\nChoose the operation letter:\n" << endl;
    cout << "a- Additon\n" << "b- Subtraction\n" << "c- Multiplicstion\n" << "d- Division\n" << endl;

    if (option == "a") {
        cout << "Additon" << endl;
        cin >> userinput01 >> userinput02;
        avareg = userinput01 + userinput02;
        cout << userinput01 << "+" << userinput02 << "= " << avareg << endl;
    }
    else if (option == "b") {
        cout << "Subtraction" << endl;
        cin >> userinput01 >> userinput02;
        avareg = userinput01 - userinput02;
        cout << userinput01 << "-" << userinput02 << "= " << avareg << endl;
    }
    else if (option == "c") {
        cout << "Multiplicstion" << endl;
        cin >> userinput01 >> userinput02;
        avareg = userinput01 * userinput02;
        cout << userinput01 << "*" << userinput02 << "= " << avareg << endl;
    }
    else if (option == "d") {
        cout << "Division" << endl;
        cin >> userinput01 >> userinput02;
        avareg = userinput01 / userinput02;
        cout << userinput01 << "/" << userinput02 << "= " << avareg << endl;
    }
    else
        cout << "You did not choose a correct letter" << endl;

    return 0;
}
Azmi Tammam
  • 23
  • 2
  • 5
  • 2
    `string option = 0;` -- What does this do? Also, since you are using Visual C++, why didn't you use the debugger to pinpoint that this line is causing the problem? A couple of `F10` key strokes would have shown this. – PaulMcKenzie Nov 01 '20 at 15:32
  • 1
    Adding `string option = 0;` to my collection of elegant ways to shoot yourself in the foot using C++... – rustyx Nov 01 '20 at 15:36

1 Answers1

5

string option = 0; is the culprit and string option; is the fix.

The latter relies on the std::string default constructor.

The former will cause the constructor to a const char* to be called, with undefined results.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483