Aaron Beaudoin
Aaron Beaudoin

Reputation: 1147

In C++, how can I make cin "cancel" if the return key is pressed?

I'm trying to learn C++ by writing a simple console application. The user navigates the main menu by entering a number stored in a variable which a switch statement then uses to determine what to do. It's pretty simple. :)

The issue that's bugging me is that when the program reaches the cin statement, pressing return without entering a number doesn't "exit" the statement but just bumps it down to the next line. I guess this makes sense, but how can I make it so pressing return with no previous input just "exits" or "cancels" the cin statement?

Below is a shortened idea of what my application sort of looks like:

int main()
{
    int mainMenuSelector;

    while(mainMenuSelector != 4){
        cout << "--- MAIN MENU -----------------" << endl;
        cout << "[1] First Option" << endl;
        cout << "[2] Second Option" << endl;
        cout << "[3] Third Option" << endl;
        cout << "[4] Exit Application" << endl;
        cout << "-------------------------------" << endl;
        cout << "Selection: ";

        cin >> mainMenuSelector;
        // This is the statement I want to move along from
        // if the user presses the return key without entering any input.

        switch(mainMenuSelector){
            case 1:
                doSomething();
                break;
            case 1:
                doSomething();
                break;
            case 2:
                doSomething();
                break;
            case 3:
                doSomething();
                break;
        }
    }
    return 0;
}

Upvotes: 0

Views: 2284

Answers (3)

Eric Sage
Eric Sage

Reputation: 86

If you're specifically looking for options which use the stream operators (rather than parsing the input yourself), you might consider std::stringstream. For example:

#include <string>
#include <iostream>
#include <sstream>

using namespace std;

void ExampleCaptureInput()
{
    int value;
    string s;
    getline(cin, s);
    if (s != "")
    {
        stringstream sstream(s);
        sstream >> value;
    }
}

Upvotes: 1

Edward Strange
Edward Strange

Reputation: 40877

std::string input;
while (std::getline(std::cin, input) && !input.empty()) { /* do stuff here */ }

You might want to go further and verify that the input is valid, doesn't just have a bunch of spaces, etc...

Upvotes: 3

Paulo
Paulo

Reputation: 1498

Pressing enter with no input results in an empty string value. You can do this (try it and adapt it to your code):

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

int main() {
    string s;
    getline(cin, s);
    while(s != "") { // if the person hits enter, s == "" and leave the loop
        cout << s << endl;
        getline(cin, s);
    }
    return 0;
}

Upvotes: 1

Related Questions