【发布时间】:2019-12-08 19:54:54
【问题描述】:
首先是代码。
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char word[20];
char blank[20];
char guess[1];
char *pch;
int life=6;
cout<<"Enter your word : ";
cin>>word;
for(unsigned int i=0;i<strlen(word);i++){
blank[i]='_';
}
cout<<blank<<endl;
while(blank != word && life >= 0){
if(strcmp(word,blank) == 0){
cout<<"Congratulations you found the word. :)";
break;
}
if(life == 0)break;
cout<<"Your guess :";
cin>>guess[0];
pch=strchr(word,int(guess[0]));
if(pch == NULL){
cout<<"Your guess is wrong try again."<<endl;
cout<<life<<endl;
}
else if(pch != NULL){
while (pch!=NULL){
blank[pch-word]=guess[0];
pch=strchr(pch+1,int(guess[0]));
}
cout<<blank<<endl;
cout<<life<<endl;
life++;
}
--life;
}
if(life == 0)cout<<"Sadly you couldn't find the word. :(";
return 0;
}
所以我想写一个刽子手代码。我设法在 Eclipse 中编写了这个非常糟糕的书面代码。它在某种程度上完成了工作,但是当尝试将其实现到代码块时,这部分程序似乎无法正常工作。
for(unsigned int i=0;i<strlen(word);i++){
blank[i]='_';
}
cout<<blank<<endl;
代码块给了我这样奇怪的输出:
Enter your word : ankara
______B
Your guess ::
或者这个:
Enter your word : adana
_____rB
Your guess :
有谁知道为什么代码块给我不同的输出? 顺便请原谅我的英语不好。
【问题讨论】:
-
如果您的数组被声明为
char blank[20],那么您只能在其中放置 19 个下划线,因为您还需要一个终止 null 才能使其成为有效的 C 字符串。 -
使用
std::string...你是在编程C++,而不是C -
@jarmod 谢谢你的回答,但我已经填了不到 19 个空格,你可以在输出中看到我得到的“ankara”这个词是 6 个字母长我的问题是代码块把这个随机'空格后的 B' 字符,例如在“ankara”输入中
-
string.h 是 C 标头。使用 cstring 或字符串。您必须使用
'\0'终止您的 cstring -
您未能创建有效的字符串。他们需要一个空终止符。您的
blank[20]字符串未初始化,因此它具有随机内容。然后在其中放置 6 个下划线,但第 7 个字符(实际上是 7 到 20)从未初始化。strcpy(blank, word)在使用下划线更新blank之前,或者在下划线之后显式写入空终止符。