Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ How to make a non void function return nothing for if else statements?

So my problem goes like this:

string something (string something){
    string letter;
    cout << "press a";
    cin >> letter;
    if (letter==a){
        return a;
    }
    else
    cout << "wrong letter";
    //what should I put here if I don't want it to return any value?
}

Any alternatives would also be welcome

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Consider using the exception mechanism for this: this carries the advantage that you can keep a reasonable return type, and you can also delegate handling of the exception to the caller of the function.

First, write

struct WrongLetterException : public std::exception{};

Then change the function to

std::string something (std::string something/*ToDo - is this correct?*/){
    std::string letter;
    std::cout << "press a";
    std::cin >> letter;
    if (letter == 'a'/*note the change here*/){
        return a;
    }
    throw WrongLetterException();
}

In the caller to the function, you then catch (const WrongLetterException& ex) and deal with it as you see fit.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading