no user input throw exception

I have a program for school that a user needs to enter a selection from a menu if they do not make a selection (enter a number 1 thru 6 ) and just press enter how do I throw an error or exception? this is not a requirement, but it is buggin me, that you can just hit enter and it drops a line and waits for the proper response (being any input ) them it processes fine. if no input is sent it drops down a line then waits . any help would be great thanks in advance.
Sounds like you're using one of the formatted input methods that skip leading whitespace (and simply hitting enter enters the endline character, which is classified as whitespace).

So, either use noskipws

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
int main()
{
    std::cin.exceptions(std::ios::failbit);
    for(;;)
    {
        int n;
        std::cin >> std::noskipws >> n;
        std::cout << "You've entered " << n << '\n';
        std::cin.ignore(); // chomp the endline
    }
}


demo: http://ideone.com/UZMbK

Or use getline()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <stdexcept>
#include <string>
int main()
{
    for(;;)
    {
        std::string line;
        getline(std::cin, line);
        if(line.empty())
                throw std::runtime_error("empty input");
        int n = stoi(line);
        std::cout << "You've entered " << n << '\n';
    }
}


demo: http://ideone.com/zcErn

Or do some other input that does not skip leading whitespace
Topic archived. No new replies allowed.