背景:此题主要注意一个地方,那就是猜对的字母再猜也算错。
思路:我是先把需要猜的那个字符串排序,然后依次判断,将其复制到另外一个字符串数组中,并在复制中剔除重复的元素,这样就可以不用考虑需要猜的字符串中哪些字符是重复的,请注意k==m1+1这个地方,为什么要加一,请读者去调试一下就知道了。然后对于猜对的字母再猜也算错这个问题,解决方法就是每判断一次,如果猜对了,就将那个赋值为空格。
学习:strchr(str,ch)函数返回的是字符ch在字符串str出现的首地址,所以在这个地方可以不用for循环再来找一遍,但笔者再写的时候对指针使用还不太熟悉,所以就用的for循环再找了一遍,读者可以自行去修改。
if(strchr(str,guess[i])!=NULL)
{
k++;
for(int gue=0;gue<=m1;gue++)
if(guess[i]==str[gue]) {str[gue]=' ';break;}
}
下面是完整代码。
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int main(void)
{
char ans[100],guess[100];
int yx;
while(scanf("%d",&yx)==1&&yx!=-1)
{
memset(ans,'a',sizeof(ans));
memset(guess,'a',sizeof(guess));
scanf("%s %s",ans,guess);
int m=strlen(ans);
printf("Round %d\n",yx);
sort(ans,ans+m);
char str[27]={'\0'};
int m1=0;
for(int i=0;i<m-1;i++)
if(ans[i]!=ans[i+1]) {str[m1]=ans[i];m1++;}
str[m1]=ans[m-1];
int j=0,k=0;
for(int i=0;i<strlen(guess);i++)
{
if(strchr(str,guess[i])==NULL) j++;
if(strchr(str,guess[i])!=NULL)
{
k++;
for(int gue=0;gue<=m1;gue++)
if(guess[i]==str[gue]) {str[gue]=' ';break;}
}
if(j==7) {printf("You lose.\n");break;}
if(k==(m1+1)) {printf("You win.\n");break;}
}
if(j<7&&k<=m1) printf("You chickened out.\n");
}
return 0;
}