gpt4 book ai didi

c - 字符串正在添加特殊字符

转载 作者:太空宇宙 更新时间:2023-11-04 03:48:29 25 4
gpt4 key购买 nike

我开始学习有关 C 的教程,然后我(从头开始)尝试编写一个程序,在该程序中,程序选择一个单词,您必须猜测字母,直到找到该单词或尝试次数用完为止。

但我卡在了字符串部分,真的很奇怪:

srand(time(NULL));
char pWord[6][15] = {"chocolate","peanut","bowling","helicopter","school","controller"}; // Possible words
int repeat=0;
int rNum = rand()%6;
char solution[strlen(pWord[rNum])];
while(repeat<strlen(pWord[rNum])) {
solution[repeat]=pWord[rNum][repeat];repeat++;
}
printf("Answer : %s", solution); printf("\n");
printf("R Answer : %s", pWord[rNum]); printf("\n");
printf("R length : %i", strlen(pWord[rNum])); printf("\n");
strcpy(solution,pWord[rNum]);

对于保龄球来说还好,但对于其他人来说它会随机添加奇怪的特殊字符。
我不知道为什么会这样(我来自 java,某个懒惰和简单的地方)。

最佳答案

在 C 中,字符串以空字符 '\0' 结尾。所以当你声明字符串solution时,你需要将char数组的长度加一,因为strlen()函数不计算末尾的空字符.

char solution[strlen(pWord[rNum])+1];

然后在while循环之后,需要将'\0'赋值给char数组的最后一个元素:

while(repeat<strlen(pWord[rNum])) {
solution[repeat]=pWord[rNum][repeat];
repeat++;
}
solution[repeat]='\0';

执行此字符串复制的更好方法是使用 strcpy() 函数而不是 while 循环:

strcpy(solution, pWord[rNum]);

这样您就不必将空字符分配给最后一个字符。此功能为您完成。

关于c - 字符串正在添加特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22571492/

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