0

I've been trying to create a bot to grab the date, time, and several more operations.

(This is my first question ever here, and I'm a bad explainer so bear with me please, hopefully you would understand me if not please don't tear me apart for lacking knowledge :)

I'm prompting the user to enter "What's the <time/date>?" it outputs the answer, then the program ends. But I don't want the program to end, I want it to prompt the user again whether to exit or re-run the program, if the user inputs 'Y' the code gets repeated, 'N' ends the program.

This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main()
{
    int hours, minutes, day, month, year;
    char user_req[50], user_prompt[3];
    
    time_t now;
    time(&now);
    
    struct tm *local = localtime(&now);
    
    hours = local->tm_hour;
    minutes = local->tm_min;
    day = local->tm_mday;
    month = local->tm_mon + 1;
    year = local->tm_year + 1900;
    

    printf("How may I help you?: ");
    scanf("%[^\n]", &user_req);
    
    if((strcmp (user_req, "What's the time?") == 0) && hours < 12){
        
        printf("\nCurrent time is: %02d:%02dAM", hours, minutes);

    } else if((strcmp (user_req, "What's the time?") == 0) && hours > 12 ){
        printf("\nCurrent time is: %02d:%02dPM", hours - 12, minutes);

    } else if(strcmp (user_req, "What's the date?") == 0){
        printf("\nCurrent date is: %d/%02d/%02d\n", year, month, day);
    } else {
        printf("\nError, please try again and follow the specific format!");
    }

    printf("\nMay I help you again? (Y/N): ");
    scanf(" %c", &user_prompt); 
    
    return 0;
}

I have tried most of the answers here(Do-While, Goto, & EOF, EOF seems to be the closest one to my case but I couldn't even import it into my piece of code since it's kinda overwhelming.):

Ask user to repeat the program or exit in C

How to use a loop function with user input in C?

I've encountered 2 bugs with Do-While & goto,

  1. After looping again, the output of the first operation is shown.
  2. After inputting 'Y' to re-run the program, instead of going to the prompt of "How may I help you?" it goes to the prompt of "May I help you again? (Y/N):"

Is it possibly because the if statements are interfering with the loops or something?

Steve Friedl
  • 3,929
  • 1
  • 23
  • 30

0 Answers0