【发布时间】:2018-04-01 03:32:58
【问题描述】:
这个程序的目的是检查用户输入的字符是否是字母数字。一旦 void 函数确认输入正确,然后将其传递给字符串测试以输出消息。我知道这不是很好的编码,但必须以这种方式完成。
我不断收到逻辑错误,我不知道为什么?有人可以帮忙吗?
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
void get_option(char& input);
/**
Takes character entered user input and loops until correct answer
@param y character entered by user
@return to main() once valid entry received
*/
string test(char);
/**
Takes checks character entered user input and loops until correct answer
@param y alphanumeric character entered by user
@return to main() once valid entry received
*/
int main()
{
char y;
//call get_option to prompt for input
get_option(y);
//call test after user input is valid
test(y);
return 0;
}
void get_option(char &x)
{
cout << "Please enter an alphanumeric character: ";
cin >> x;
while (!(isdigit(x)||islower(x)||isupper(x)))
{
cout << "Please enter an alphanumeric character: ";
cin >> x;
}
}
string test(char y)
{
if (isupper(y))
{
cout << "An upper case letter is entered!";
} else if (islower(y)) {
cout << "A lower case letter is entered!";
} else if (isdigit(y)) {
cout << "A digit is entered!";
}
return "";
}
【问题讨论】:
-
为什么将
test声明为返回一个string,然后从中返回0(不是字符串),然后完全忽略它的返回值? -
有一个东西叫
isalpha()。此外,如果您使用char作为输入,像isalpha()这样的函数在技术上具有未定义的行为,因为它需要unsigned chars。您应该先将其转换为无符号字符。 en.cppreference.com/w/cpp/string/byte/isdigit -
更好的是,std::isalnum() 检查字母数字字符。
标签: c++ alphanumeric