我已经习惯了这个c程序一段时间了,我似乎无法弄清楚我错过了什么。
在我的代码的最底部,我有一个函数用“ - ”替换每个其他单词。 我的问题是,当我输入一个奇数字,例如“猫”,“狗”,“汉堡包”时,它会在我认为的空字符位置放置一个“ - ”,尽管我还没有能够揭穿它。
感谢您的帮助!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void replace(char w[]);
int main( )
{
char w[100], x[100], y[100];
int z = 0;
printf("Player 1, please enter the secret word: ");
fgets(x,100,stdin);
// system("clear");
while( strcmp(x,y) != 0 )
{
strcpy(w,x);
// printf("\nLength of String : %d", strlen(w)-1);
replace(w);
printf("Player 2, the word is %s\n",w);
printf("Player 2, please guess the word: ");
fgets(y,100,stdin);
z++;
if( strcmp(x,y) != 0 )
{
printf("Wrong. Try again.\n");
}
else
{
//system("clear");
printf("Correct!\n");
printf("It took you %d attempt(s).\n",z);
switch (z)
{
case 1 :
case 2 :
printf("A. Awesome work!");
{break;}
case 3 :
case 4 :
printf("B. Best, that was!");
{break;}
case 5 :
case 6 :
printf("C. Concentrate next time!");
{break;}
case 7 :
printf("D. Don't quit your day job.");
{break;}
default :
printf("F. Failure.");
{break;}
}
}
}
getch();
}
void replace(char w[])
{
int a;
a = 0;
while (w[a] != '\0')
{
if (a % 2 != 0)
{
w[a] = '-';
a++;
}
if (w[a] != '\0')
{
a++;
}
else
{
break;
}
}
}
答案 0 :(得分:2)
来自fgets manual
;
fgets()从流中读取最多一个小于大小的字符,并将它们存储到s指向的缓冲区中。读数在EOF或换行符后停止。 如果读取换行符,则将其存储到缓冲区中。 终止空字节(\ 0)存储在缓冲区中的最后一个字符之后。
输入的换行符就是您要替换的内容。
答案 1 :(得分:0)
你可以这样实现......
int a;
int len;
a = 0;
len = strlen(w);
if(len%2 == 0)
len = len-1;
while (len!=a)
{
if (a % 2 != 0)
{
w[a] = '-';
a++;
}
if (w[a] != '\0')
{
a++;
}
else
{
break;
}
}
答案 2 :(得分:0)
我认为只用fgets
替换gets
会有效:
尝试:
//fgets(x,100,stdin);
gets(x);
和
//fgets(y,100,stdin);
gets(y);
我认为这就足够了。
答案 3 :(得分:0)
问题是由传递给replace函数的char数组中的附加'\ n'字符引起的。
例如,当输入为“Cat”时,传递的char [] w包含{'C','a','t','\ n','\ 0'}; 附加的'\ n'也会被“ - ”字符替换。
以下将解决此问题。
while (w[a] != '\0')
{
if (w[a] != '\0' && w[a] != '\n')
{
if (a % 2 != 0)
{
w[a] = '-';
}
a++;
}
else
{
break;
}
}
答案 4 :(得分:0)
稍微提一下,我可以建议以不同的方式构造你的replace()代码
void replace(char charw[])
{
int length=strlen(charw);
int i;
for (i=0;i<length;i++)
{
if (i%2==1) /*yes, i%2 would also work, but lets not get too clever*/
{charw[i]='-';}
}
}
这更具可读性。在循环中间打破......不是那么多。