ok so this is my code for some Movie rental thing there seems to be no problem during compile time but in runtime when i enter some character in cin >> choice; (choice variable) it jumps couple of steps forward and instead of printing (cout << "Please provide the following info:";) it creates a mess, run it ur selves and u will see:
#ifndef _MOVIE_PROMPTER_HPP_
#define _MOVIE_PROMPTER_HPP_
/*
* This is just what I like to do, but instead of having the 'using namespace' clause
* I prefer to individually document what's used. Probably a lot of people won't agree and
* will think it's just extra unnecessary code.
*/
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::getchar;
using std::numeric_limits;
using std::streamsize;
/**
* The concept modularized in a class
*/
class MoviePrompter
{
public:
staticvoid PromptForMovie(void)
{
char customerName[20], movieName[20];
unsignedint numberOfDays;
unsignedchar choice;
cout << "Please give customer name: ";
cin.getline(customerName, 19);
cout << "Please provide movie description" << endl;
cout << "Enter 'R' for Romance Movie" << endl;
cout << "Enter 'P' for Popular Movie" << endl;
cout << "Enter 'N' for New Release" << endl;
cout << "Enter 'K' for Kids" << endl;
choice = toupper(getchar()); // notice the toupper method - it will set the input to uppercase if possible
//Validate the user's input
while(choice != 'R' && choice != 'P' && choice != 'N' && choice != 'K')
{
cout << "Invalid Selection" << endl;
cout << "Please provide movie description" << endl;
cout << "Enter 'R' for Romance Movie" << endl;
cout << "Enter 'P' for Popular Movie" << endl;
cout << "Enter 'N' for New Release" << endl;
cout << "Enter 'K' for Kids" << endl;
choice = toupper(getchar());
cout << endl;
}
//Ignore the extraneous data in the stream
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Please provide the following info:" << endl;
cout << "Movie Name? ";
cin.getline(movieName, 19);
cout << endl;
cout << "Number of days? ";
cin >> numberOfDays;
//Here, we check for input failure. This occurs, for example, if you try to put 'adasfaewdfsfa' into an integer variable
while(!cin)
{
cin.clear(); //reset the fail state
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //Ignore the extraneous data
cout << "Invalid entry" << endl;
cout << "Numer of days? ";
cin >> numberOfDays;
}
int totalAmount;
switch (choice)
{
case'R':
totalAmount = numberOfDays*40;
break;
case'P':
totalAmount = numberOfDays*80;
break;
case'N':
totalAmount = numberOfDays*120;
break;
case'K':
totalAmount = numberOfDays*20;
break;
}
cout << "Your Rental Amount is: " << totalAmount << endl;
}
};
#endif // _MOVIE_PROMPTER_HPP_
/*
* Now, to use our class, see below
*/
int main()
{
//PromptForMovie is a static member function of the MoviePrompter class.
MoviePrompter::PromptForMovie();
return 0;
}