【发布时间】:2021-12-18 10:30:38
【问题描述】:
我只是 C/编程世界的菜鸟/新手。我将首先发布代码,然后我将描述我的问题。
#include <stdio.h>
#include <string.h>
int
main ()
{
char f[30], j[30] = "mount everest";
int s,a=0;
printf ("\n");
printf ("2) Which is the tallest mountain in the world?\n");
printf ("\n");
printf ("Please type your answer below\n");
scanf("%[a-z]s",f);
s = strcmp (f, j);
printf ("\n");
if (s == 0)
{
printf ("Congratulations! You have recieved a point!\n");
a++;
}
else
{
printf ("Sorry! Better luck next time!");
a--;
}
return 0;
}
因此,当我尝试将答案键入“珠穆朗玛峰”时,输出会直接转到我的“else”(对不起!下次祝你好运!)语句。另外,我希望程序只接受小写字母(我已经将它定义为在整个测验过程中要遵循的严格规则)。
**OUTPUT**
2) Which is the tallest mountain in the world?
Please type your answer below
mount everest
Sorry! Better luck next time!
但是当我在 if 条件中使用 (not)'!s' 而不是 's' 时,它满足 if 条件并将消息打印为 'Congratulations!您获得了积分!'。我真的不知道这是怎么回事?我对其他 2 个问题采用了相同的方法,并且没有这个“!”它们都可以正常工作。问题。
#include <stdio.h>
#include <string.h>
int
main ()
{
char f[30], j[30] = "mount everest";
int s,a=0;
printf ("\n");
printf ("2) Which is the tallest mountain in the world?\n");
printf ("\n");
printf ("Please type your answer below\n");
scanf("%[a-z]s",f);
s = strcmp (f, j);
printf ("\n");
if (!s == 0)
{
printf ("Congratulations! You have recieved a point!\n");
a++;
}
else
{
printf ("Sorry! Better luck next time!");
a--;
}
return 0;
}
**OUTPUT**
2) Which is the tallest mountain in the world?
Please type your answer below
mount everest
Congratulations! You have recieved a point!
所以有人可以向我解释正在发生的事情(因为我是新手,所以我有点不知道如何理解调试)以及我在这里做错了什么?另外,如果您无法从这部分代码中理解,我将在此处发布整个代码,但现在我认为它太繁琐了,所以如果您愿意,请告诉我!感谢您花时间解决我的问题。非常感谢任何帮助。
编辑
在你们/贡献者的有用评论的帮助下,我再次编写了代码(感谢大家抽出时间帮助这个新手)现在我将向您展示修改后的/新的代码优先:
#include <stdio.h>
#include <string.h>
int
main ()
{
char f[30], j[30] = "mount everest";
int s,a=0;
printf ("\n");
printf ("2) Which is the tallest mountain in the world?\n");
printf ("\n");
printf ("Please type your answer below\n");
fgets(f,15,stdin);
printf("%s\n",f);
printf("%s\n",j);
printf ("\n");
s=strcmp(f,j);
if (s==0)
{
printf ("Congratulations! You have recieved a point!\n");
a++;
}
else
{
printf ("Sorry! Better luck next time!");
a--;
}
return 0;
}
但现在我又被抛回了 else 条件。像这样:
Output
2) Which is the tallest mountain in the world?
Please type your answer below
mount everest
mount everest
mount everest
Sorry! Better luck next time!
我知道“if”条件存在问题,但似乎无法弄清楚它是什么。因此,如果有人能检测到我的错误,那么我会非常高兴。再次感谢大家对我的帮助。
【问题讨论】:
-
strcmp 返回 0 如果字符串匹配,你写的条件是
!s == 0s==0 -
调试提示:使用
printf("[%s]\n", f)查看f中存储的内容。 -
%[a-z]只读取字母;mount和everest之间有一个空格。一种可能的解决方法是在字符集中添加一个空格。还要注意,%[…]是一个扫描集并且是完整的;它不是%s的修饰符,因此不需要%[a-z]s中的s。一般来说,它会导致问题,尽管您不会在这里注意到它们。 -
我将使用 printf("[%s]\n", f) 并让您知道。非常感谢!
-
"%[a-z]"转换将在找到任何不是小写字母的字符时停止。这意味着当它在mount之后找到空格字符时它会停止。您可以尝试将空格字符添加到允许的字符集中,例如"%[a-z ]"。就个人而言,我会使用fgets阅读整行(but you'll have to remove the newline thatfgetsputs in the buffer)。
标签: c string if-statement char stdio