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++ function must return a value

I’m trying to make a program where I have a password in before it but it just says:

admission must return a value

And I do not understand what to do about it.

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

string Admission() {
  string userinput;                // users guess
  string password = "passwordlol"; // actual password

  cout << "Enter password:" << endl;
  cin >> userinput;

  if (userinput != password) {
    cout << "Wrong password, please try again" << endl;
    cin >> userinput;

    while (userinput != password)
      cout << "Wrong password, please try again" << endl;

    cin >> userinput;
  } else
    cout << "Correct password, welcome in.";
}

int main() {
  cout << Admission() << endl;
  system("pause>nu1");

>Solution :

The issue has been mentioned in the comments. I just want to correct your code a bit.

  1. std::endl slows down your program because of unnecessary flushes. Use '\n' instead.
  2. system("pause>nu1"); is non-portable code. Use std::cin.get() or another portable alternative.
  3. Your loop is not good. Use a do-while loop instead of the if-else statement that has a while-loop inside.
  4. It’s good to declare a variable close to where it will be used. We’re not coding in pre-C99!!! This also reduces your mental load of memorizing where a variable can be modified. So you won’t have to worry much.
#include <iostream>


void Admission()
{
    std::string password = "passwordlol"; // actual passaword
    std::cout << "Enter password:\n";

    bool isCorrect { };

    do
    {
        std::string userinput; // users guess
        std::cin >> userinput;

        if ( userinput != password )
        {
            std::cout << "Wrong password, please try again\n";
        }
        else
        {
            isCorrect = true;
        }

    } while ( !isCorrect );

    std::cout << "Correct password, welcome in.\n";
}

int main( )
{
    Admission( );

    std::cin.get( );
}
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