Which is better among these?
Code:
unsigned short method1(const string& text = "", unsigned short max = -1){
string ins;
unsigned short val;
while (true)
{
cout << text;
getline(cin, ins);
try
{
val = stoi(ins);
if (val > max) throw val;
}
catch (...)
{
cout << "Invalid answer!\n\n";
continue;
}
break;
}
return val;
}
Code:
unsigned short method2(const string& text = "", unsigned short max = -1){
unsigned short val;
while (true)
{
cout << text;
if (cin >> val && val <= max) break;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid answer!\n\n";
}
return val;
}
The results are the same, but I'm going to use this function many times so I want to be sure that I'm using the best performing one