Originally Posted by
peckitt99
Code:
cout << "WASHING MACHINE HAS BEEN DISABLED PLEASE CONTACT YOUR SUPPLIER";
Where in the world do washing machines require a passcode and go out of order if it's wrong?
Originally Posted by
peckitt99
how can i stop this and make it carry on looping untill the write password is entered?
You will need a loop. Only stop the loop when the passcode is right or when the number of errors reaches the limit. cin can fail if a number format isn't read so you will need to test for that too. I wrote something that's probably too heavy duty for what you want, but I got caught up in getting it to work just like I wanted on every error condition. streams are wierd and fun at the same time. I also set the code up so that you can test it with other streams.
Code:
#include <cassert>
#include <ios>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
namespace Hikaru
{
class format_error: public std::runtime_error
{
public:
explicit format_error(const std::string& message)
: runtime_error(message) {}
virtual ~format_error() {}
};
bool PassCode(std::istream& is, std::ostream& err = std::cerr)
{
const int errorsAllowed = 3;
int errors = 0;
do
{
const int code = 1205;
int userCode;
if (!(is >> userCode))
{
if (is == std::cin)
{
err << "Number format required\n";
is.clear();
}
else
{
throw format_error("Bad stream format");
}
}
if (is == std::cin)
{
assert(is.rdbuf()->in_avail() > 0 && "\"cin >> number\" always leaves '\n'");
is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
if (userCode != code)
{
if (is == std::cin)
{
err << "Please try again> ";
}
++errors;
}
else
{
break;
}
}
while (errors < errorsAllowed);
assert(errors <= errorsAllowed);
return errors < errorsAllowed;
}
}
I'm sorry, working problems like these is a great way to test new stuff I've learned.