0

i'm still in the beggining of learning C/C++, and i'm trying to figure out how to prevent certain inputs from the user in a simple program. I would like to know how to prevent inputs such as empty input, 1 123123 that would make instruction variable = 1, but i wanted the program to give an error.

#include <iostream>
#include <limits>
using namespace std;
int instruction() {
    int instruction;
    cout << "Do you want to see the tutorial of the game? If yes press: 1, else press: 0" << endl << "--> ";
    while (!(cin >> instruction) || (instruction != 1 &&  instruction != 0)){
        cout <<"Error: Must introduce 1 or 0" << endl << "--> ";
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(),'\n');
    }
    cout << instruction;

    return 0;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Note: Please don't tag unrelated languages. This question is, obviously, not about C. – Algirdas Preidžius Mar 20 '20 at 00:15
  • 1
    Open your C++ book to the chapters that explain how to use `std::getline`, and `std::istringstream`, and read them. – Sam Varshavchik Mar 20 '20 at 00:17
  • It is hard to write good, fool proof interactive console programs; it's a typical beginner exercise -- normally such programs expect input from some source (file, pipe, whatever). They must verify that the format is proper and give a proper diagnosis if not, but that's all. Interactive programs these days almost always are GUI programs, with better means to control and verify input. So don't waste too much time on the intricacies of istreams, and go towards GUIs. – Peter - Reinstate Monica Mar 20 '20 at 00:31

0 Answers0