It appears to work for me. the only possible thing I can see that might not compile is that you forgot the std:: prefix to the string parameter.
The only logical confusion I have is if this if condition is correct? It seems superfluous since you are using the index [] operator to retrieve that character. (Not saying it's wrong, it might just be redundant).
Code:
if (i > 1) {std::cout << invalid_char_input() << std::endl;
}
I tested it with the following code, it worked correctly AFAIK:
Code:
#include <string>
#include <iostream>
using namespace std;
class UserInputHandler
{
public:
char GetSingleCharacter(std::string limit);
std::string invalid_char_input()
{
return std::string("You must enter a single character.");
}
std::string char_not_allowed()
{
return std::string("That character is forbidden.");
}
};
char UserInputHandler::GetSingleCharacter(std::string limit)
{
std::string str;
char letter;
int i;
bool loopend = false;
while (loopend == false) {
std::getline(std::cin, str);
i = (int)str.length();
if (std::string::npos == str.find_first_not_of(limit)) {
if (i > 1) {
std::cout << invalid_char_input() << std::endl;
} else {
letter = str[0];
std::cout << "Character Entered: " << letter << endl;
loopend = true;
}
} else {
std::cout << char_not_allowed() << std::endl;
}
}
return letter;
}
int main()
{
UserInputHandler uih;
uih.GetSingleCharacter("abcd");
}