c - 试图创建一个猜测我的字母代码。如何合并用户输入的字符等于我的字母的情况?
问题描述
我正在尝试创建一个程序,将用户输入的字母与我的字母进行比较。如果字母相同,程序应该说它们相同,然后终止。如果它们不相同,则应提示用户输入另一个字符,直到他们猜对为止。
我尝试嵌套一个 if 语句并嵌套一个 while 循环来实现字母相等的情况。
#include <stdio.h>
int main()
{
char myLetter = 'a';
printf("insert a char:");
char userLetter;
scanf("%1s", &userLetter);
while (userLetter != myLetter)
{
printf("%c does not match mine, try again:", userLetter);
scanf("%1s", &userLetter);
}
while (userLetter == myLetter)
{
printf("char matches! program will terminate now. ");
break;
}
}
预期的:
insert a char:h
h does not match mine, try again:j
j does not match mine, try again:g
g does not match mine, try again:f
f does not match mine, try again:a
char matches! program will terminate now.
实际的:
insert a char:h
h does not match mine, try again:j
j does not match mine, try again:g
g does not match mine, try again:f
f does not match mine, try again:a
a does not match mine, try again:a does not match mine, try again:^C
解决方案
读取单个字符的正确格式运算符是%c
, not %1s
。后者读取单个字符,但将其写入以空字符结尾的字符串,因此它将在userLetter
变量外部写入空字节,这会导致未定义的行为。
您应该在操作符之前放置一个空格,以便scanf
在读取字符之前跳过空格。这是使它在每次响应后忽略换行符所必需的。
您还应该在每次提示后关闭输出缓冲或刷新缓冲区,因为它们不会以换行符结尾。
最后不需要while
循环,因为在字符匹配之前您不会退出第一个循环。
这是一个工作版本:
#include <stdio.h>
int main()
{
char myLetter = 'a';
setbuf(stdout, NULL);
printf("insert a char:");
char userLetter;
scanf(" %c", &userLetter);
while (userLetter != myLetter)
{
printf("%c does not match mine, try again:", userLetter);
scanf(" %c", &userLetter);
}
printf("char matches! program will terminate now.\n");
}
推荐阅读
- powershell - 这个错误是什么意思 Set-Location “path” 在 Powershell 中为空?
- vue.js - Vue js - 如何在数据和方法中使用道具
- amazon-web-services - 如何在 Elastic Beanstalk (AWS) 上部署多容器?
- java - 我如何在java(Excel)中写入特定列并读取特定列?
- c - 如何调用 execl(或 simlar)并为子进程设置信号处理程序?
- r - 如何避免R中的for循环遍历数据框的变量
- c# - 为具有 C# .NET Core 3.1 属性的组成员返回 Active Directory
- r - 如何修复 R 中未定义的列选择错误?
- linux - 推送到 linux 服务器时无法运行 rsync
- mobile - Foundation JS Orbits - 仅用于小型展示