1

Hi i dont know how to allow the user to choose one of the choices i provided in my code and if they picked a choice that was not given then i want the program to return to the last point.

This is my code

#include <iostream>
#include <string>

using namespace std;

int main()
{

//Welcoming message with date//
cout << "Welcome to FILM Screen Cinema" << endl;


cout << endl;
cout << "ENTER STAFF/OPERATOR'S NAME: ";
string name;
cin >> name;

cout << endl;
cout << "ENTER DATE:";
string date;
cin >> date;

cout << endl;
cout << "CHOOSE A MOVIE THAT IS SCREENING TODAY:" << endl;
cout << "[1] Deadpool" << endl << "[2] Goosebumps" <<endl;
string input;
cin >> input;


}

Where it says choose a movie, i want the user to type either 1 or 2 for the choices but if they type any other number then it should say invalid and allow them to type 1 or 2 again. Thank you in advance.

David Yaw
  • 27,383
  • 4
  • 60
  • 93
goat
  • 7
  • 1
  • 2
  • 5

1 Answers1

1

I suspect you want each of the std::cin >> XXX calls to actually query the user for input. That is currently not the case, for example when the user types "John Smith" as the name of the operator, name will be set to "John", and the following std::cin >> date reuses the remaining part "Smith" instead of asking for input again.

To fix this, you can use std::getline.

The first part of your code should thus be replaced by

std::cout << '\n';
std::cout << "ENTER STAFF/OPERATOR'S NAME: ";
std::string name;
std::getline(std::cin, name);

std::cout << '\n';
std::cout << "ENTER DATE:";
std::string date;
std::getline(std::cin, date);

std::cout << '\n';

The same is true for the part where you validate the input. Now you only need to add a while-loop to keep asking the user for new input if the previous one was invalid.

std::cout << "CHOOSE A MOVIE THAT IS SCREENING TODAY:\n";
std::cout << "[1] Deadpool\n"
          << "[2] Goosebumps\n";

std::string input;
std::getline(std::cin, input);

while(input != "1" && input != "2") {
    std::cout << "Invalid!\n\n";

    std::cout << "CHOOSE A MOVIE THAT IS SCREENING TODAY:\n";
    std::cout << "[1] Deadpool\n"
              << "[2] Goosebumps\n";
    std::getline(std::cin, input);
}

if (input == "1") {
    // do something
} else if (input == "2") {
    // do something else
}

Btw, please consider reading “\n” or '\n' or std::endl to std::cout? and Why is “using namespace std” considered bad practice?

Community
  • 1
  • 1
Corristo
  • 4,911
  • 1
  • 20
  • 36