error handling - C++ Prevent CMD Commands being used -
apologies (previous?) poorly worded question
i trying prevent cmd commands being used. f6 button can't work around. entering f6 closes program or loops username() function.
due f6 or ctr+z being direct command enter loop. has caused program act un-predictably. on 1 machine loops infinitely, on own shuts downt window
part of assessment has been driving me nuts since started it. many of peers having issues it, direct request it's immediate 'fail' if can crash our program. thats why i'm being persistent on allowing characters defined below:
size_t found = user.find_first_not_of("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz1234567890");
as requested enough of program replicate problem:
#include <iostream> #include <sstream> #include <vector> #include <cmath> #include <ctime> #include <cstdlib> #include <string> #include <istream> #include <cstddef> string name = { "" }; int menu(); int errorchecking(string user); int username(); int main() { cout << "-------------------- welcome! --------------------" << endl << endl; username(); } int errorchecking(string user) { size_t found = user.find_first_not_of("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz1234567890"); if (found != string::npos) { cout << name[found] << " not acceptable character." << '\n'; cout << "enter valid name "; cout << endl << endl; username(); } return(0); } int username() { cout << "enter name: "; std::getline(cin, name); //if (name == "→") { cin.clear(); username(); } errorchecking(name); return(0); }
the problem ctrlz keystroke, @ windows terminal prompt, indicates "end of file". when cin
encounters end of file, stream enters error state , no further calls std::getline(cin, name)
wait user type input.
what need handle stream error state appropriately. 1 way might be:
cout << "enter name: "; std::getline(cin, name); if (!cin) { cerr << "unexpected end of file encountered on cin\n"; exit(1); } errorchecking(name);
you may of course take whatever other action instead of calling exit(1)
.
Comments
Post a Comment