【发布时间】:2018-01-23 15:15:34
【问题描述】:
这里是初学者。 我正在尝试制作一个向用户询问谜语的游戏。 正确答案是这样写的当前时间:hh:mm
程序运行良好,直到用户输入许多不同的错误猜测(如随机字母)。 之后即使答案是正确的也会报错。
代码如下:
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <stdbool.h>
int main(){
//check
bool ok=false; //true when guess==real time
int tent=0; //tryes
//guesses
char tempo[5]; //input string from user
char ora[2]; //houres
char min[2]; //mins
//get time
time_t my_time;
struct tm * timeinfo;
time (&my_time);
timeinfo = localtime (&my_time);
//random
srand(time(NULL));
//guessing game, user shound input a string that conains current time to win: hh:mm
printf("In principio era uno, e il nulla.\n\n");
printf("Poi l'uomo lo duplico', e tra essi traccio' la via...\n");
printf("Lo fece ancora... e gli sembro' perfetto.\n");
printf("Ma non era abbastanza... ");
printf("Cosi' si spinse piu' in profondita', e sbirciando poco oltre trovo'... ");
do{
//get guessed time (could also get words and non relevant numbers, if input is not hh:mm (current hour:current mins) user gets error)
scanf("%s",&tempo);
fflush(stdin);
//split array tempo into ora and min to separate h from mins
ora[0]=tempo[0];
ora[1]=tempo[1];
min[0]=tempo[3];
min[1]=tempo[4];
//cast guess form string to int
int oraint=atoi(ora); //creat integer hour from string
int minint=atoi(min); //integer mins
//check guess == real time
if(oraint==timeinfo->tm_hour && minint==timeinfo->tm_min){
//win
printf("\nCOMPLIMENTI! Hai trovato la risposta!\n");
printf("\n\nEcco le tue prossime istruzioni!\n\n");
printf("TURFeE1UQXdNREF3TVRFd01EQXdNVEF4TVRFd01ERXhNREV4TVRBd01URXdNVEV4TURFeE1UQXhNVEF4TVRFeE1ERXhNVEF3TVRBd01URXdNREV3TURBd01URXhNREV3TURBeE1EQXdNREF3TVRBd01ERXhNREF4TVRBeE1URXhNREV4TVRBeE1ERXdNVEV4TURBeE1EQXhNVEV3TVRBd01ERXhNREV3TURBd01UQXdNREV3TURBeE1UQXhNREF4TURFeE1ERXhNREV3TVRFd01ERXdNVEF4TVRBeE1URXdNREV4TVRBd01URXdNVEV3TVRBd01UQXhNVEF4TVRFeE1ERXhNREV4TVRBPQ==\n\n");
printf("Che c'e'? devo anche dirti come decifrarle?\n");
printf("...e va bene...ti do un'indizio\n");
printf("Ricorda che, a volte, un colpo non basta.");
ok=true;
} else {
tent++;
int val=rand()%6; //random error pharases
switch(val){
case 0:
printf("Non ci siamo...\n\n");
break;
case 1:
printf("Pare di no...\n\n");
break;
case 2:
printf("Riprova.\n\n");
break;
case 3:
printf("Pensaci meglio...\n\n");
break;
case 4:
printf("Nah, prova ancora.\n\n");
break;
case 5:
printf("Ti ho mai detto quante risposte hai gia' provato?\n");
printf("Beh... sono ben ");
printf("%d\n\n",tent);
break;
}
}
}while(ok=true);
getchar();
return 0;
}
我正在尝试我没有研究过的东西,所以请原谅愚蠢的错误或糟糕的代码。提前感谢
【问题讨论】:
-
while(ok=true);肯定是错的。 -
请正确缩进您的代码。机器(编译器)可以读取和编译任何东西,但是对于人类来说,它需要在将文本块读取为 code 时做出一点sense。提问时,文本区域右侧有一个橙色的大如何格式化框。还有一个完整的格式化辅助工具栏。还有一个 [?] 按钮提供格式化帮助。还有一个预览区域,显示您的帖子发布后的样子。使您的帖子清晰,并证明您花时间这样做,可以提高您获得好答案的机会。
-
试试
while(ok==true);(注意==操作符) -
fflush(stdin);调用未定义的行为。 -
@edtheprogrammerguy:为什么不
while(ok!=true);?