这个程序的目的是检查用户输入的字符是否是字母数字。一旦 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(char)
函数的返回类型让程序完美运行:
#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
*/
int test(char); //Changed from string to int
/**
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;
}
}
int test(char y) //Also changed from string to int
{
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 0;
}
(使用 C++14 编译器在 JDoodle 上进行测试。) (另外,使用 Xcode 进行了测试。仍然有效)
关于c++ - 检查输入是否为字母数字时出现逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49594545/