我们的教授要求我们编写一个程序来确定输入的字符是符号,数字还是字母。有什么方法可以将if-else语句转换为PURE switch语句。我一直想知道如何。
#include <iostream>
using namespace std;
main()
{
char a;
cout << "Enter a single character: " ;
cin >> a;
switch ((a >= 65 && a <= 90) || (a >= 97 && a <= 122)) //ASCII Value 65-90 (capital letters), 97-122 (small letters)
{
case 1:
cout << "You entered a letter!";
break;
case 0:
if (a >= 48 && a <= 57 ) //ASCII Value 48-57 (num 0-9)
{
cout << "You entered a number!" << endl;
}
else
{
cout << "You entered a symbol!" << endl;
}
break;
}
return 0;
}
最佳答案
可能是这样吗?您可以将编译时间反射添加为练习=)
#include <iostream>
enum class CType
{
Letter,
Digit,
Symbol
};
CType getType(char a)
{
if( (a >= 65 && a <= 90) || (a >= 97 && a <= 122) )
return CType::Letter;
if( a >= 48 && a <= 57 )
return CType::Digit;
return CType::Symbol;
}
CType getType2(char a) // more explicit
{
if( (a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z') )
return CType::Letter;
if( a >= '0' && a <= '9' )
return CType::Digit;
return CType::Symbol;
}
#include <cctype>
CType getType3(char a) // warning: that functions uses locale inside
{
if( isalpha(a) )
return CType::Letter;
if( isdigit(a) )
return CType::Digit;
return CType::Symbol;
}
int main(...)
{
char a;
std::cout << "Enter a single character: " ;
std::cin >> a;
switch(getType(a)) {
case CType::Letter:
std::cout << "You entered a letter!";
break;
case CType::Digit:
std::cout << "You entered a number!";
break;
case CType::Symbol:
std::cout << "You entered a symbol!";
break;
}
return 0;
}
UPD:从评论中添加其他解决方案
关于c++ - 需要帮助确定输入的字符是符号,数字还是字母,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45323380/