SKmay
SKmay

Reputation: 39

use snprintf in printing integer values

The code below is converting a number of seconds to the DD:HH:MM format. Instead of using printf, I would like to use snprintf. How should I print those d,h,m in the snprintf?

#include <stdio.h>

#define LONGEST 60

int main() {
    int sec, h, m, s, d, temp; 
    char *temp_str;
    int test= 2835656; 
    d = test / 86400; //divide the number of seconds by the number of seconds in a day
    if (d < 100) {
        temp = test % 86400; 
        temp /= 60;  // 
        h = temp / 60; //to get "minute" 
        m = temp % 60; //to get "second"
    } else {
        d = 99;
        h = 23;
        m = 59;
    }

    printf("DD:HH:MM:%d:%d:%d\n", d, h, m); //output is DD:HH:MM:32:19:40

    return 0;
}

I tried snprintf(temp_str, LONGEST, "%02s:%02s:%02s", d, h, m); but it didn't work

Upvotes: 2

Views: 1426

Answers (2)

chqrlie
chqrlie

Reputation: 144951

You must define temp_str as an array of char with at least LONGEST elements, andd you can use the same format string as for printf.

Note however that your format string should be "%02d:%02d:%02d" to produce 2 digits for each field even for values below 10.

Here is a modified version:

#include <stdio.h>

#define LONGEST 60

int main() {
    int sec, h, m, s, d, temp; 
    char temp_str[LONGEST];
    int test = 2835656;

    d = test / 86400; //divide the number of seconds by the number of seconds in a day
    if (d < 100) {
        temp = test % 86400; 
        temp /= 60;    // discard the seconds
        h = temp / 60; // to get "hour" 
        m = temp % 60; // to get "minute"
    } else {
        d = 99;
        h = 23;
        m = 59;
    }

    snprintf(temp_str, LONGEST, "DD:HH:MM:%02d:%02d:%02d\n", d, h, m); //output is DD:HH:MM:32:19:40
    fputs(temp_str, stdout);

    return 0;
}

Upvotes: 1

Blaze
Blaze

Reputation: 16876

Why the different format string for the snprintf attempt? Just do it like you did in the printf call:

snprintf(temp_str, LONGEST, "DD:HH:MM:%d:%d:%d", d, h, m);

The %02s specifier doesn't work for integers. You also haven't declared temp_str, so you need to do that beforehand:

char temp_str[LONGEST];

After calling snprintf, the string "DD:HH:MM:32:19:40" is stored in temp_str and you can verify that with puts(temp_str);, for instance.

Upvotes: 3

Related Questions