比较字符串与C中的整数

标签 c arrays string char int

初学者在这里。 我正在尝试制作一款向用户提问谜语的游戏。 正确答案是当前时间这样写: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;
}

我正在试验我没有研究过的东西,所以请原谅愚蠢的错误或错误的代码。提前致谢

最佳答案

这里的一些问题:

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

一行一行:

scanf("%s",&tempo);

在将数组表达式如 tempo 传递给 scanf 时,不要使用 & 运算符 - 在大多数情况下,数组表达式会自动转换为指针表达式情况。该行应该只是

scanf("%s", tempo);

其次,tempo 不够大,无法存储 string "hh:mm"- 请记住,字符串总是以 0 结尾。您需要分配一个至少比您打算在其中存储的最长字符串大 1 个元素的数组,因此 tempo 应声明为 char[6]

第三,

fflush(stdin);

一般没有定义; “刷新”输入流根本没有多大意义。确实,Microsoft 将其定义为在其特定实现中清除输入流,但总的来说,该行是无意义的。不要指望它能在 MSVC 实现之外的任何地方工作。

下一步,

ora[0]=tempo[0];
ora[1]=tempo[1];
min[0]=tempo[3];
min[1]=tempo[4];

tempooramin 不是字符串 - 你没有为一个字符串终止符。 atoi 不会正确转换它们。

您必须将 oramin 都声明为 char[3],并确保 ora[2 ]min[2] 设置为 0:

ora[0] = tempo[0];
ora[1] = tempo[1];
ora[2] = 0;
min[0] = tempo[3];
min[1] = tempo[4];
min[2] = 0;

当然,您可以使用以下方法避免所有这一切:

int ora;
int min;

if ( scanf( "%d:%d", &ora, &min ) == 2 )
{
  // read ora and min properly
} 
else
{
  // bad input or error
}

最后,

while(ok=true);

必须是其中之一

while ( ok == true ); // == for comparison, = for assignment

while ( ok ); // my personal preference

ok=true assignstrueok - 要执行比较,使用 好的 == 真

关于比较字符串与C中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405040/

相关文章:

mysql - 准备好的 SELECT 语句执行但始终返回 0 行

javascript - Lodash 从混合数组和对象中获取叶子

javascript - 如何读取从 ajax 返回的数据数组以获取 google 图表?

c# - 如何通过正则表达式检查和提取字符串?

c - 链表问题 - 循环迭代错误的节点

c - 为什么我在 C 中的多维动态分配不起作用?

javascript - 将唯一 id 添加到深层嵌套对象数组的最有效方法

c - 如何保存字符串标记,将其内容保存到数组中,然后使用这些内容进行进一步比较

javascript 输出未显示在 html 中

C 在 linux 和 windows 上获取 cpu 使用率