gpt4 book ai didi

c++ - 输入奇数时打印空字符

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:32 27 4
gpt4 key购买 nike

我已经研究这个 c 程序一段时间了,但我似乎无法弄清楚我遗漏了什么。

在我的代码的最底部,我有一个用“-”替换所有其他单词的函数。我的问题是,当我输入一个奇数编号的单词时,例如“Cat”、“dog”、“hamburger”,它会在我认为是空字符的位置放置一个“-”,尽管我无法做到揭穿它。

感谢您的帮助!

    #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;
}
}
}

最佳答案

来自fgets manual ;

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (\0) is stored after the last character in the buffer.

输入的换行符就是您要替换的内容。

关于c++ - 输入奇数时打印空字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20626534/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com