Reputation: 99
cout << "Options:\n1: Change Name\n2: Change Password\n3: Change Address\n4: Withraw\n5: Deposit\nL: Log out\n>";
while (user_input2 != '1' && user_input2 != '2' && user_input2 != '3' && user_input2 != '4' && user_input2 != '5' && user_input2 != 'L')
{
cout << "Invalid input";
}
So how do I just shortened the while conditions?
I tried doing:
cout << "Options:\n1: Change Name\n2: Change Password\n3: Change Address\n4: Withraw\n5: Deposit\nL: Log out\n>";
while (user_input2 != '1','2','3','4','5','L')
{
cout << "Invalid input";
}
but it doesn't work.
edit1: "I added more hints to what I wanted to do"
Upvotes: 4
Views: 246
Reputation: 310983
You can use the <
and >
operators for the range of '1'
to '5'
, but you'll have to handle the check for 'L'
explicitly:
while (user_input2 != 'L' && (user_input2 < '1' || user_input2 > '5'))
{
cout << "Invalid input";
}
Upvotes: 9
Reputation: 20141
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";
}
}
Btw. there is a standard C library function (adopted in C++ standard) which could be used as well:
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";
}
}
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
Upvotes: 2
Reputation: 51
You also can write:
while (user_input2 != '1' && user_input2 != '2' && user_input2 != '3' && user_input2 !=
'4' && user_input2 != '5')
{
cout << "Invalid input"
}
Upvotes: 3