英文:
If char was only to be used with an if statement, how can it be used with an %c or %s?
问题
以下是您要翻译的内容:
问题出在以下这段代码。
基本上,我感到困惑,因为我知道char
应该与%c
匹配。
但我也知道%c
只能获取一个字符,这意味着为了获取if语句中的单词('man'或'woman'),它必须变成%s
。
但是,%s
又无法与char
匹配。
我想问一下:
如果我保持char不变,
我的想法和代码中的问题是什么,导致结果无法正确输出?
int main() {
char gender;
printf("输入性别(M/F):");
scanf("%c", &gender);
if (scanf("%c", &gender) == 'M') {
printf("男性");
}
else if (scanf("%c", &gender) == 'F') {
printf("女性");
}
printf("性别是 %c。", gender);
return 0;
}
英文:
The problem I'm getting at is with this following code.
Basically, I'm confused since I know that char
should be matched with %c
.
Yet, I also know that %c
gets only one character, which means that in order to get the word in the if statement ('man' or 'woman'), it has to become a %s
.
But then, %s
doesn't match with char
.
I would like to ask:
if I were to leave char as it is,
what would be the problem with my idea and code that is making the result unable to come out properly?
int main() {
char gender;
printf("Enter gender(M/F) : ");
scanf("%c", &gender);
if (scanf("%c", &gender) == 'M') {
printf("Man");
}
else if (scanf("%c", &gender) == 'F') {
printf("Woman");
}
printf("The gender is %c.", gender);
return 0;
}
答案1
得分: 2
Sure, here are the translated code parts:
为什么不使用getchar()呢?
int main()
{
printf("输入性别(M/F):");
char gender = getchar();
if (gender == 'M')
printf("男性\n")
if (gender == 'W')
printf("女性\n")
printf("性别是 %c。\n", gender);
return 0;
}
另外,将您的读取部分封装到while循环中并且只有当从用户获取的字符可接受时才退出它是一种良好的做法(检查EOF或任何其他字符,显示错误消息并重试)。
或者只需使用scanf一次:
int main()
{
printf("输入性别(M/F):");
char gender;
scanf(" %c", &gender);
if (gender == 'M')
printf("男性\n")
if (gender == 'W')
printf("女性\n")
printf("性别是 %c。\n", gender);
return 0;
}
英文:
Why don't you use the getchar() instead?
int main()
{
printf("Enter gender(M/F) : ");
char gender = getchar();
if (gender == 'M')
printf("Man\n")
if (gender == 'W')
printf("Woman\n")
printf("The gender is %c.\n", gender);
return 0;
}
Also its a good practice to enclosure your reading into a while loop and break from it only if the char that you got from the user is acceptable (Check for EOF or any other char , show an error message and try again.)
Alternative just use scan only one time:
int main()
{
printf("Enter gender(M/F) : ");
char gender;
scanf(" %c", &gender);
if (gender == 'M')
printf("Man\n")
if (gender == 'W')
printf("Woman\n")
printf("The gender is %c.\n", gender);
return 0;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论