在这段“联系人管理系统”的代码中,我很难获得一行的预期输出。基本上,在这一部分中,当您添加新联系人时,它会要求您“请输入公寓#”,如下所示:
if (yes() == 1)
{
printf("Please enter the contact's apartment number: ");
address->apartmentNumber = getInt();
if (address->apartmentNumber > 0)
{
}
else
{
printf("*** INVALID INTEGER *** <Please enter an integer>: ");
address->apartmentNumber = getInt();
}
}
else
{
address->apartmentNumber = 0;
}
现在,根据我的作业,您应该输入单词(而不是数字,明白吗?)“bison”,它会显示输出:
* INVALID INTEGER * Please enter an integer:
就上下文而言,这部分工作得非常好。但是,您会被指示输入整数“-1200”,然后会出现提示
* INVALID APARTMENT NUMBER * Please enter a positive number:
这部分是我遇到问题的,因为简单地说,我不知道把它放在哪里,无论是在 if 语句中还是在 if 语句之外。我不确定,并且希望得到一些帮助。
我试图自己纠正这个问题,但它只是给了我双倍的无效整数输出,而不是这个正确的无效公寓号语句。这是我的(失败的)尝试:
if (yes() == 1)
{
printf("Please enter the contact's apartment number: ");
address->apartmentNumber = getInt();
if (address->apartmentNumber > 0)
{
}
else
{
printf("*** INVALID INTEGER *** <Please enter an integer>: ");
address->apartmentNumber = getInt();
}
if (address->apartmentNumber < 0)
{
}
else
{
printf("*** INVALID APARTMENT NUMBER *** <Please enter a positive number>: ");
address->apartmentNumber = getInt();
}
else
{
address->apartmentNumber = 0;
}
编辑:对于那些要求 getInt() 和 yes() 代码的人,这里:
getInt()
int getInt(void)
{
int num;
char nl;
scanf("%d%c", &num, &nl);
while (nl != '\n') {
clearKeyboard();
printf("*** INVALID INTEGER *** <Please enter an integer>: ");
scanf("%d%c", &num, &nl);
}
return num;
}
和 yes():
int yes(void)
{
int yesno, flag;
char c, nl;
scanf("%c%c", &c, &nl);
do {
if (nl != '\n') {
clearKeyboard();
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
flag = 1;
scanf("%c%c", &c, &nl);
}
else if (c != 'Y' && c != 'y' && c != 'N' && c != 'n') {
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
flag = 1;
scanf("%c%c", &c, &nl);
}
else if (nl == '\n' && (c == 'Y' || c == 'y' || c == 'N' || c == 'n'))
{
flag = 0;
}
} while (flag == 1);
if (c == 'Y' || c == 'y') {
yesno = 1;
}
else {
yesno = 0;
}
return yesno;
}
最佳答案
getInt
将处理非整数(文本和单词)输入,并重新提示用户输入整数,直到用户输入为止。
所以你的代码需要更像这样:
if (yes() == 1)
{
int validNumber = 0;
while (validNumber == 0)
{
printf("Please enter the contact's apartment number: ");
address->apartmentNumber = getInt();
if (address->apartmentNumber > 0)
{
validNumber = 1;
}
else
{
printf("* INVALID APARTMENT NUMBER * Please enter a positive number:\n");
}
}
}
关于c - 我该如何修复 C 中的 if 语句以使其按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55437086/