【问题标题】:Compare string to integer in C将字符串与C中的整数进行比较
【发布时间】: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);

标签: c arrays string char int


【解决方案1】:

这里有一些问题:

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 时不要使用&amp; 运算符 - 在大多数情况下,数组表达式会自动转换为指针表达式。那条线应该是

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 分配trueok - 要进行比较,请使用 ok == true

【讨论】:

  • 非常感谢,非常感谢您的帮助和时间,正如我所说,我刚刚开始学习 C,所以您和所有的 cmets 真的很宝贵!
猜你喜欢
  • 1970-01-01
  • 2021-08-10
  • 2020-07-01
  • 2016-01-16
  • 2020-04-15
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多