1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
#include <algorithm>
#include <string>
void GetInput(std::string question, std::string &name);
void CheckName(std::string &name, std::string &rightname);
int main ()
{
std::string name, rightname;
GetInput("Brave adventurer, what is your name? \n-> ", name);
CheckName(name, rightname);
while (rightname != "Y" and rightname != "YES")
{
GetInput("\nOh, I'm sorry, I'm a little deaf, must be my old age. So, what is your name? \n-> ", name);
CheckName(name, rightname);
}
return 0;
}
void GetInput(std::string question, std::string &name)
{
do
{
std::cout << question;
getline (std::cin, name);
while (name[0] == ' ')
name.erase ( name.begin() );
} while ( name.empty() );
}
void CheckName(std::string &name, std::string &rightname)
{
std::string question = "\nYour name is ";
question.append(name);
question.append(", right?\n");
unsigned found;
while (true)
{
found = name.find_first_not_of(" ABCDEFGHIJKLMNOPRSTUVWXYZabcdefghijklmonprstuvwxyz0123456789");
if (found != std::string::npos)
{
std::cout << "The first invalid character is " << name[found];
std::cout << " at position " << found << "\n\n";
}
else break;
GetInput("\nYour name contained invalid characters, please choose another name: \n-> ", name);
}
GetInput(question, rightname);
std::transform( rightname.begin(), rightname.end(), rightname.begin(),
[]( char c ) { return ( toupper( c ) ); } );
}
|