How about a function where you provide all accepted characters as string?
Demo:
#include <iostream>
bool checkValid(char cChk, std::string_view allowed)
{
for (char c : allowed) if (cChk == c) return true;
return false;
}
int main()
{
char user_input2;
std::cin >> user_input2;
if (!checkValid(user_input2, "12345L")) {
std::cout << "Invalid input\n";
}
}
Live Demo on coliru
Btw. there is a standard C library function (adopted in C++ standard) which could be used as well:
std::strchr()
It returns a pointer to found character or nullptr
and could be used similar like checkValid()
in the above sample:
#include <cstring>
#include <iostream>
int main()
{
char user_input2;
std::cin >> user_input2;
if (!std::strchr("12345L", user_input2)) {
std::cout << "Invalid input\n";
}
}
Live Demo on coliru
Thinking twice (about OPs possible intention), I started to ask why the check is needed at all. Assuming that the valid input has to be processed somehow (I would use a switch
for this), invalid input just could be covered as well.
Demo:
#include <iostream>
int main()
{
for (char user_input2; std::cin >> user_input2;) {
switch (user_input2) {
case '1': std::cout << "Change Name\n"; break;
case '2': std::cout << "Change Password\n"; break;
case '3': std::cout << "Change Address\n"; break;
case '4': std::cout << "Withraw\n"; break;
case '5': std::cout << "Deposit\n"; break;
case 'l': case 'L': std::cout << "Log out\n"; return 0;
default: std::cerr << "Invalid input!\n";
}
}
}
Input:
12AL
Output:
Change Name
Change Password
Invalid input!
Log out
Live Demo on coliru