Ok I was able to validate user input if the user would enter a larger number or a negative number but how do you validate if the user happens to enter a letter or word, even character i.e % # @, or if the user enters all. How do you block the user to only enter a number for example 1 to 6?

Also, What about if the user presses space? Please show examples.

Is there an easier way as to using ASCII character set in maybe a switch case.

Recommended Answers

All 2 Replies

Read the entire line as a string and look at the input character by character.

You post your code that shows your attempt and explains what happened. Then we will help you make corrections.

How do you block the user to only enter a number for example 1 to 6?

You write your own raw input handler to read keystrokes and interpret them as desired. It should go without saying that this is terribly confusing unless you own the canvas[1] or are taking input from a GUI[2]. A much easier and more user-friendly method is simply to allow the user to type whatever he or she wants, then validate it and respond accordingly:

#include <iostream>
#include <stdexcept>
#include <boost/lexical_cast.hpp>

int main() try
    int value;
    while (true) {        
        std::cout << "Enter a number from 1 to 6: ";
        std::string line;
        if (!getline(std::cin, line))
            throw std::runtime_error("Invalid input");
        try {
            value = boost::lexical_cast<int>(line);
            if (value >= 1 && value <= 6)
                std::cerr << "Out of range\n";
        } catch (boost::bad_lexical_cast&) {
            std::cerr << "Invalid number" << '\n';
    std::cout << "The square of " << value << " is " << value * value << '\n';
} catch (std::exception& ex) {
    std::cerr << "Fatal error: " << ex.what() << '\n';

[1] ie. You're using a "primitive" graphics engine such as curses to draw in the console.
[2] In which case you should be using an appropriate input control for numeric values rather than straight text.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.