0

I noticed if when prompted to enter my choice, if I press enter (creating an empty line) it didn't detect my input as a 0 length input but rather it just allowed me to enter on the next line down. How do I stop this in an easy way so even if its an empty input it still registers

#include <iostream>
int main()
{
    std::string MMOption; //Main Menu Option
    std::cout << "Main Menu" << std::endl;
    while (MMOption != "6") {
        std::cout << "1. New Account" << std::endl;
        std::cout << "2. View Account/s" << std::endl;
        std::cout << "3. Edit Account" << std::endl;
        std::cout << "4. Delete Account" << std::endl;
        std::cout << "5. Option's" << std::endl;
        std::cout << "6. Exit" << std::endl;
        std::cin >> MMOption;
        std::cout << std::endl;
    }
}

Thanks in advance

Evorage
  • 493
  • 3
  • 15

3 Answers3

2

By default input using >> skips (reads and discard) any leading white-space, which includes newlines.

To detect empty lines as input you need to read full lines, for example using std::getline and then check if it's empty or not.

Note that if the user input leading spaces (normal space, tab, etc.) then it will be added in the string read by std::getline, and you need to strip or trim such leading spaces. And maybe trailing spaces as well. See e.g. this old answer for how to trim leading/trailing spaces from a string.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

By default, this will not get any empty values if you press return.

        std::cin >> MMOption;

However, you can opt in to use the Standard Get Line method. Which is std::getline

#include <iostream>
#include <string>
int main()
{
    std::string MMOption; //Main Menu Option
    std::cout << "Main Menu" << std::endl;
    while (MMOption != "6") {
        std::cout << "1. New Account" << std::endl;
        std::cout << "2. View Account/s" << std::endl;
        std::cout << "3. Edit Account" << std::endl;
        std::cout << "4. Delete Account" << std::endl;
        std::cout << "5. Option's" << std::endl;
        std::cout << "6. Exit" << std::endl;
        std::getline(std::cin, MMOption);
        std::cout << std::endl;
    }
}

Check out this link for the online demo http://cpp.sh/3pwze

CodingSomething
  • 449
  • 3
  • 10
0

Instead of:

std::cin >> MMOption;

you can do:

std::getline(std::cin, MMOption);

which will read empty lines as well. std::getline needs #include <string> as well.

cigien
  • 57,834
  • 11
  • 73
  • 112