d7994 d7994 - 1 year ago 82
C++ Question

Outputting time in minutes and seconds C++

Firstly, I know homework is looked down on but I'm not asking anyone to complete this for me, just to guide a little. I've looked online but answers vary and are different and because I'm new it's a little confusing.

I need to make a program where the user inputs the name of a snail and the time taken for it to complete a lap of a track... The time needs to be put in in seconds but put out in minutes&seconds.

Currently have;


int main() {

char snail_name[15] = "";
char time_taken[1000] = "";

printf("\nEnter name of snail: ");
scanf("%s", &snail_name);
printf("Time to finish course:");
scanf("%s", &time_taken);
printf("%s ran the course in\n", &snail_name,&time_taken);

Currently have:


Which means I need it to say ran the course in 5 minutes(300 was entered for example), although the code currently doesn't work for that but I could figure that out probably, just need to know how I go about converting a number input by the user to be shown in minutes and seconds.

Answer Source

Accept the total time as an integer instead of a string, and then you can divide it by 60 to get whole minutes and modulus of 60 to get the remaining seconds:

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

int main() {
    char snail_name[15] = "";
    int time_taken = 0;

    printf("\nEnter name of snail: ");
    scanf("%15s", snail_name);
    printf("Time to finish course:");
    scanf("%d", &time_taken);
    printf("%s ran the course in %d:%d\n", &snail_name, time_taken / 60, time_taken % 60);

    return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download