简体   繁体   中英

Compare string to integer in C

beginner student here. I'm trying to make a game where the user is asked a riddle. the correct answer is the current time written like this: hh:mm

The program works fine until the user inputs to many different wrong guesses (like random letters). After that it gives error even if the answer is right.

Here is the code:

#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;
}

I'm experimenting with thing I didn't study, so please forgive stupid errors or bad code.. Thanks in advance

Some problems here:

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

Going line by line:

scanf("%s",&tempo);

Do not use the & operator when passing an array expression like tempo to scanf - array expressions are automatically converted to pointer expressions under most circumstances. That line should simply be

scanf("%s", tempo);

Secondly, tempo isn't large enough to store the string "hh:mm" - remember that a string always has a terminating 0. You need to allocate an array that's at least 1 element larger than the longest string you intend to store in it, so tempo should be declared as char[6] .

Third,

fflush(stdin);

is not defined in general; "flushing" an input stream simply doesn't make much sense. It's true that Microsoft defined it to clear out the input stream in their particular implementations, but in general the line is nonsensical. Don't expect it to work anywhere outside of a MSVC implementation.

Next,

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

Like tempo , ora and min are not strings - you haven't set aside any space for a string terminator. atoi will not convert them properly.

You'll have to declare both ora and min as char[3] , and make sure that ora[2] and min[2] are set to 0:

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

Of course, you can avoid all of this by using the following:

int ora;
int min;

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

Finally,

while(ok=true);

needs to be either

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

or

while ( ok ); // my personal preference

ok=true assigns the value true to ok - to perform a comparison, use ok == true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM