Distant Graphics February 2016

Unintialized local variable 'e' used

I have this code. It should work perfectly. It's a circle calculator; I'm doing is as an exercise. I want the user to have the option to return the the 'main menu.' I made a yes/no prompt using char* e; but it's uninitialized. How can I initialize

#include <iostream>

using namespace std;

class Circlecalc {
public:
    double const pi = 3.1415962543;
    double diameter;
    double radius;
    double circumference;

};

int _welcome() {
    Circlecalc calc;
    cout << endl;
    int i = 0;
    char* e;
    cin >> i;
    while (i != 5)
    {
        switch (i) {
        case(1) :
            cout << "Enter your radius." << endl;
            cin >> calc.radius;
            cout << endl;
            cout << (calc.radius * 2) * calc.pi << endl;
            cout << "Exit? [Y/N]" << endl;
            cin >> e;
            if (e == "Y") {
                _welcome();
            }

            else if (e == "N") {
            }

            else {
                cerr << "Unsupported function" << endl;
            }

        case(2) :
            cout << "Enter your diameter" << endl;
            cin >> calc.diameter;
            cout << endl;
            cout << (calc.diameter * 2) * calc.pi << endl;
            cout << "Exit? [Y/N]" << endl;
            cin >> e;
            if (e == "Y") {
                _welcome();
            }

            else if (e == "N") {
            }

            else {
                cerr << "Unsupported function" << endl;
            }
            break;

        case(3) :
            cout << "Enter the circumference" << endl;
            cin >> calc.circumference;
            cout << endl;
            cout << (calc.circumference / 2) / calc.pi;
            cout << "Exit? [Y/N]" << endl;
            cin >> e;
            if (        

Answers


marcinj February 2016

Instead of:

char* e;

use:

std::string e;

The reason you get:

Unintialized local variable 'e' used

is that e is not set when passed to operator>> that is used by cin, to initialize it assign an array to it, ie:

char arr[128] = {0};
char* e = arr;

operator>> for cin stream expect that you have provided some memory buffer where read string is located, char* e; is not bound to any such buffer, and that would end in (possibly) crash (Undefined Behaviour).


NathanOliver February 2016

In this case you do not need to. If you only want a single letter input from the user just use a char like

char response;

Then you would compare it against a character literal instead of a string literal like

if (response == 'N' || response == 'n')

If you want to compare against a string like "no" or "No" then I suggest you use a std::string and not worry about having to allocate memory for the string.

Post Status

Asked in February 2016
Viewed 2,292 times
Voted 12
Answered 2 times

Search




Leave an answer