Return two last digits of an integer as string in C











up vote
2
down vote

favorite
1












I have a 3 digit integer myInt:



int myInt = 809;


I need an output string *myStr which consists of the 2 last digits. Therefore



char *mystr = "09";


What would be the easiest solution to do that?










share|improve this question




















  • 4




    What have you tried? How did your attempt work or not work? Please read about how to ask good questions, as well as this question checklist. Lastly learn how to create a Minimal, Complete, and Verifiable Example.
    – Some programmer dude
    Nov 7 at 7:53






  • 1




    Apart from asking on SO and being told? What have you tried, and what problems did you run into? Show us your code for your best effort so far and we can help set you in the right direction. The interesting part is how you allocate the storage for the string containing the answer. There are many ways to do it, depending in part on how much you know of C and mostly depending on whether the code is in a function or in main() — another reason we need to see your best effort. Please read about how to create an MCVE (Minimal, Complete, and Verifiable example).
    – Jonathan Leffler
    Nov 7 at 7:53








  • 2




    As a couple of hints: The modulo operator (%) and the snprintf function could be useful here.
    – Some programmer dude
    Nov 7 at 7:54












  • char *mystr does not define a "string", but just a pointer to a char. Defining it does not allocate any space to store any char.
    – alk
    Nov 7 at 8:15

















up vote
2
down vote

favorite
1












I have a 3 digit integer myInt:



int myInt = 809;


I need an output string *myStr which consists of the 2 last digits. Therefore



char *mystr = "09";


What would be the easiest solution to do that?










share|improve this question




















  • 4




    What have you tried? How did your attempt work or not work? Please read about how to ask good questions, as well as this question checklist. Lastly learn how to create a Minimal, Complete, and Verifiable Example.
    – Some programmer dude
    Nov 7 at 7:53






  • 1




    Apart from asking on SO and being told? What have you tried, and what problems did you run into? Show us your code for your best effort so far and we can help set you in the right direction. The interesting part is how you allocate the storage for the string containing the answer. There are many ways to do it, depending in part on how much you know of C and mostly depending on whether the code is in a function or in main() — another reason we need to see your best effort. Please read about how to create an MCVE (Minimal, Complete, and Verifiable example).
    – Jonathan Leffler
    Nov 7 at 7:53








  • 2




    As a couple of hints: The modulo operator (%) and the snprintf function could be useful here.
    – Some programmer dude
    Nov 7 at 7:54












  • char *mystr does not define a "string", but just a pointer to a char. Defining it does not allocate any space to store any char.
    – alk
    Nov 7 at 8:15















up vote
2
down vote

favorite
1









up vote
2
down vote

favorite
1






1





I have a 3 digit integer myInt:



int myInt = 809;


I need an output string *myStr which consists of the 2 last digits. Therefore



char *mystr = "09";


What would be the easiest solution to do that?










share|improve this question















I have a 3 digit integer myInt:



int myInt = 809;


I need an output string *myStr which consists of the 2 last digits. Therefore



char *mystr = "09";


What would be the easiest solution to do that?







c character






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 7 at 9:03









Antti Haapala

78k16147189




78k16147189










asked Nov 7 at 7:51









MasovyKnedlicek

416




416








  • 4




    What have you tried? How did your attempt work or not work? Please read about how to ask good questions, as well as this question checklist. Lastly learn how to create a Minimal, Complete, and Verifiable Example.
    – Some programmer dude
    Nov 7 at 7:53






  • 1




    Apart from asking on SO and being told? What have you tried, and what problems did you run into? Show us your code for your best effort so far and we can help set you in the right direction. The interesting part is how you allocate the storage for the string containing the answer. There are many ways to do it, depending in part on how much you know of C and mostly depending on whether the code is in a function or in main() — another reason we need to see your best effort. Please read about how to create an MCVE (Minimal, Complete, and Verifiable example).
    – Jonathan Leffler
    Nov 7 at 7:53








  • 2




    As a couple of hints: The modulo operator (%) and the snprintf function could be useful here.
    – Some programmer dude
    Nov 7 at 7:54












  • char *mystr does not define a "string", but just a pointer to a char. Defining it does not allocate any space to store any char.
    – alk
    Nov 7 at 8:15
















  • 4




    What have you tried? How did your attempt work or not work? Please read about how to ask good questions, as well as this question checklist. Lastly learn how to create a Minimal, Complete, and Verifiable Example.
    – Some programmer dude
    Nov 7 at 7:53






  • 1




    Apart from asking on SO and being told? What have you tried, and what problems did you run into? Show us your code for your best effort so far and we can help set you in the right direction. The interesting part is how you allocate the storage for the string containing the answer. There are many ways to do it, depending in part on how much you know of C and mostly depending on whether the code is in a function or in main() — another reason we need to see your best effort. Please read about how to create an MCVE (Minimal, Complete, and Verifiable example).
    – Jonathan Leffler
    Nov 7 at 7:53








  • 2




    As a couple of hints: The modulo operator (%) and the snprintf function could be useful here.
    – Some programmer dude
    Nov 7 at 7:54












  • char *mystr does not define a "string", but just a pointer to a char. Defining it does not allocate any space to store any char.
    – alk
    Nov 7 at 8:15










4




4




What have you tried? How did your attempt work or not work? Please read about how to ask good questions, as well as this question checklist. Lastly learn how to create a Minimal, Complete, and Verifiable Example.
– Some programmer dude
Nov 7 at 7:53




What have you tried? How did your attempt work or not work? Please read about how to ask good questions, as well as this question checklist. Lastly learn how to create a Minimal, Complete, and Verifiable Example.
– Some programmer dude
Nov 7 at 7:53




1




1




Apart from asking on SO and being told? What have you tried, and what problems did you run into? Show us your code for your best effort so far and we can help set you in the right direction. The interesting part is how you allocate the storage for the string containing the answer. There are many ways to do it, depending in part on how much you know of C and mostly depending on whether the code is in a function or in main() — another reason we need to see your best effort. Please read about how to create an MCVE (Minimal, Complete, and Verifiable example).
– Jonathan Leffler
Nov 7 at 7:53






Apart from asking on SO and being told? What have you tried, and what problems did you run into? Show us your code for your best effort so far and we can help set you in the right direction. The interesting part is how you allocate the storage for the string containing the answer. There are many ways to do it, depending in part on how much you know of C and mostly depending on whether the code is in a function or in main() — another reason we need to see your best effort. Please read about how to create an MCVE (Minimal, Complete, and Verifiable example).
– Jonathan Leffler
Nov 7 at 7:53






2




2




As a couple of hints: The modulo operator (%) and the snprintf function could be useful here.
– Some programmer dude
Nov 7 at 7:54






As a couple of hints: The modulo operator (%) and the snprintf function could be useful here.
– Some programmer dude
Nov 7 at 7:54














char *mystr does not define a "string", but just a pointer to a char. Defining it does not allocate any space to store any char.
– alk
Nov 7 at 8:15






char *mystr does not define a "string", but just a pointer to a char. Defining it does not allocate any space to store any char.
– alk
Nov 7 at 8:15














5 Answers
5






active

oldest

votes

















up vote
3
down vote



accepted










Here is a simple solution:



#include <stdio.h>

int main(void) {
char buf[3];
char *myStr;
unsigned int myInt = 809;

buf[0] = myInt / 10 % 10 + '0'; /* tens digit */
buf[1] = myInt % 10 + '0'; /* unit digit */
buf[2] = ''; /* null terminator */
myStr = buf;

puts(mystr);
return 0;
}





share|improve this answer




























    up vote
    4
    down vote













    You can do like this:



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

    int main(int argc, char **argv)
    {
    char buf[32];
    int myInt = 809;
    char* mystr;
    snprintf(buf, sizeof buf, "%d", myInt);
    if (strlen(buf) > 2)
    mystr = buf + strlen(buf) - 2;
    else
    mystr = buf;
    fputs(mystr, stdout);
    return 0;
    }





    share|improve this answer























    • Amazing! Thank you!
      – MasovyKnedlicek
      Nov 7 at 8:01






    • 1




      20 is a magic number, here. It is sufficient for the current architectures where sizeof(int) <= 4, but it may be wrong in a theoretical architecture where sizeof(int )== 8. It would be better to put the actual maximum length if an int, like the size needed to print INT_MIN.
      – Giovanni Cerretani
      Nov 7 at 9:02




















    up vote
    2
    down vote













    For the specific case of turning "magic numbers" into strings, you can as well do that at compile-time. That is, when you have an integer constant rather than a run-time value:



    #include <stdio.h>

    #define VAL 809

    #define STRINGIFY(x) #x
    #define STR(i) STRINGIFY(i)
    #define SUBSTR(i, n) &(STRINGIFY(i))[n]

    int main (void)
    {
    int whatever = VAL;

    puts(STR(VAL));
    puts(SUBSTR(VAL, 1));

    return 0;
    }


    Output:



    809
    09





    share|improve this answer





















    • Your substr does not count backwards. But it too can be done; you could show it :D
      – Antti Haapala
      Nov 7 at 9:04










    • @AnttiHaapala The OP didn't request that, but of course doing so in the pre-processor is trivial :) For your amusement: onlinegdb.com/BJkeNVgTX
      – Lundin
      Nov 7 at 9:45










    • So what's wrong with &STRINGIFY(i)[sizeof (STRINGIFY (i)) - n - 1]?
      – Antti Haapala
      Nov 7 at 9:53












    • @AnttiHaapala It reads out of bounds of the string literal...? Not sure if I understand what you mean.
      – Lundin
      Nov 7 at 9:57










    • #define RIGHT(i, n) &(STRINGIFY(i))[sizeof STRINGIFY(i) - 1 - n] puts(RIGHT(VAL, 2));
      – Antti Haapala
      Nov 7 at 10:21




















    up vote
    2
    down vote













    No pointer magic necessary here. Just use plain math (the remainder operator: %), along with some suitable formatting:



    #include <stdio.h>

    int main(void)
    {
    char a[3]; /* 2 characters for any value >= 0 and < 100. So we rely on the 100 below.
    +1 character for the `0`-terminator to make this a C-string*/
    int i = 809;

    assert(i >= 0);

    sprintf(a, "%02d", i % 100);

    puts(a);
    }


    or avoiding magic numbers:



    #include <stdio.h>

    long long power_integer(int base, int x)
    {
    if (0 == x)
    {
    return 1;
    }

    return base * power_integer(x - 1);
    }

    #define CUTOFF_BASE (10)
    #define CUTOFF_DIGITS (2)

    int main(void)
    {
    char a[3];
    char f[8]; /* To hold "%01lld" to "%019lld".
    (A 64 bit integer in decimal uses max 19 digits) */

    int i = 809;

    assert(i >= 0);

    sprintf(f, "%%0%dlld*, CUTOFF_DIGITS);
    sprintf(a, f, i % power_integer(CUTOFF_BASE, CUTOFF_DIGITS));

    puts(a);
    }


    Output would be:



    09





    share|improve this answer






























      up vote
      1
      down vote













      You could try something like this:



      #include <stdio.h>
      #include <string.h>
      int main(int argc, char **argv){
      int myInt = 809;
      char buf[16]; // buffer big enough to hold the string representation
      sprintf(buf, "%d", myInt); // write the string to the buffer
      char* myStr = &buf[strlen(buf) - 2]; // set a pointer to the second last position
      printf("myStr is %sn", myStr);
      return 0;
      }





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














         

        draft saved


        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53185370%2freturn-two-last-digits-of-an-integer-as-string-in-c%23new-answer', 'question_page');
        }
        );

        Post as a guest
































        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        3
        down vote



        accepted










        Here is a simple solution:



        #include <stdio.h>

        int main(void) {
        char buf[3];
        char *myStr;
        unsigned int myInt = 809;

        buf[0] = myInt / 10 % 10 + '0'; /* tens digit */
        buf[1] = myInt % 10 + '0'; /* unit digit */
        buf[2] = ''; /* null terminator */
        myStr = buf;

        puts(mystr);
        return 0;
        }





        share|improve this answer

























          up vote
          3
          down vote



          accepted










          Here is a simple solution:



          #include <stdio.h>

          int main(void) {
          char buf[3];
          char *myStr;
          unsigned int myInt = 809;

          buf[0] = myInt / 10 % 10 + '0'; /* tens digit */
          buf[1] = myInt % 10 + '0'; /* unit digit */
          buf[2] = ''; /* null terminator */
          myStr = buf;

          puts(mystr);
          return 0;
          }





          share|improve this answer























            up vote
            3
            down vote



            accepted







            up vote
            3
            down vote



            accepted






            Here is a simple solution:



            #include <stdio.h>

            int main(void) {
            char buf[3];
            char *myStr;
            unsigned int myInt = 809;

            buf[0] = myInt / 10 % 10 + '0'; /* tens digit */
            buf[1] = myInt % 10 + '0'; /* unit digit */
            buf[2] = ''; /* null terminator */
            myStr = buf;

            puts(mystr);
            return 0;
            }





            share|improve this answer












            Here is a simple solution:



            #include <stdio.h>

            int main(void) {
            char buf[3];
            char *myStr;
            unsigned int myInt = 809;

            buf[0] = myInt / 10 % 10 + '0'; /* tens digit */
            buf[1] = myInt % 10 + '0'; /* unit digit */
            buf[2] = ''; /* null terminator */
            myStr = buf;

            puts(mystr);
            return 0;
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 7 at 8:33









            chqrlie

            57.9k745100




            57.9k745100
























                up vote
                4
                down vote













                You can do like this:



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

                int main(int argc, char **argv)
                {
                char buf[32];
                int myInt = 809;
                char* mystr;
                snprintf(buf, sizeof buf, "%d", myInt);
                if (strlen(buf) > 2)
                mystr = buf + strlen(buf) - 2;
                else
                mystr = buf;
                fputs(mystr, stdout);
                return 0;
                }





                share|improve this answer























                • Amazing! Thank you!
                  – MasovyKnedlicek
                  Nov 7 at 8:01






                • 1




                  20 is a magic number, here. It is sufficient for the current architectures where sizeof(int) <= 4, but it may be wrong in a theoretical architecture where sizeof(int )== 8. It would be better to put the actual maximum length if an int, like the size needed to print INT_MIN.
                  – Giovanni Cerretani
                  Nov 7 at 9:02

















                up vote
                4
                down vote













                You can do like this:



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

                int main(int argc, char **argv)
                {
                char buf[32];
                int myInt = 809;
                char* mystr;
                snprintf(buf, sizeof buf, "%d", myInt);
                if (strlen(buf) > 2)
                mystr = buf + strlen(buf) - 2;
                else
                mystr = buf;
                fputs(mystr, stdout);
                return 0;
                }





                share|improve this answer























                • Amazing! Thank you!
                  – MasovyKnedlicek
                  Nov 7 at 8:01






                • 1




                  20 is a magic number, here. It is sufficient for the current architectures where sizeof(int) <= 4, but it may be wrong in a theoretical architecture where sizeof(int )== 8. It would be better to put the actual maximum length if an int, like the size needed to print INT_MIN.
                  – Giovanni Cerretani
                  Nov 7 at 9:02















                up vote
                4
                down vote










                up vote
                4
                down vote









                You can do like this:



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

                int main(int argc, char **argv)
                {
                char buf[32];
                int myInt = 809;
                char* mystr;
                snprintf(buf, sizeof buf, "%d", myInt);
                if (strlen(buf) > 2)
                mystr = buf + strlen(buf) - 2;
                else
                mystr = buf;
                fputs(mystr, stdout);
                return 0;
                }





                share|improve this answer














                You can do like this:



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

                int main(int argc, char **argv)
                {
                char buf[32];
                int myInt = 809;
                char* mystr;
                snprintf(buf, sizeof buf, "%d", myInt);
                if (strlen(buf) > 2)
                mystr = buf + strlen(buf) - 2;
                else
                mystr = buf;
                fputs(mystr, stdout);
                return 0;
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 7 at 9:17

























                answered Nov 7 at 7:57









                Yunbin Liu

                930110




                930110












                • Amazing! Thank you!
                  – MasovyKnedlicek
                  Nov 7 at 8:01






                • 1




                  20 is a magic number, here. It is sufficient for the current architectures where sizeof(int) <= 4, but it may be wrong in a theoretical architecture where sizeof(int )== 8. It would be better to put the actual maximum length if an int, like the size needed to print INT_MIN.
                  – Giovanni Cerretani
                  Nov 7 at 9:02




















                • Amazing! Thank you!
                  – MasovyKnedlicek
                  Nov 7 at 8:01






                • 1




                  20 is a magic number, here. It is sufficient for the current architectures where sizeof(int) <= 4, but it may be wrong in a theoretical architecture where sizeof(int )== 8. It would be better to put the actual maximum length if an int, like the size needed to print INT_MIN.
                  – Giovanni Cerretani
                  Nov 7 at 9:02


















                Amazing! Thank you!
                – MasovyKnedlicek
                Nov 7 at 8:01




                Amazing! Thank you!
                – MasovyKnedlicek
                Nov 7 at 8:01




                1




                1




                20 is a magic number, here. It is sufficient for the current architectures where sizeof(int) <= 4, but it may be wrong in a theoretical architecture where sizeof(int )== 8. It would be better to put the actual maximum length if an int, like the size needed to print INT_MIN.
                – Giovanni Cerretani
                Nov 7 at 9:02






                20 is a magic number, here. It is sufficient for the current architectures where sizeof(int) <= 4, but it may be wrong in a theoretical architecture where sizeof(int )== 8. It would be better to put the actual maximum length if an int, like the size needed to print INT_MIN.
                – Giovanni Cerretani
                Nov 7 at 9:02












                up vote
                2
                down vote













                For the specific case of turning "magic numbers" into strings, you can as well do that at compile-time. That is, when you have an integer constant rather than a run-time value:



                #include <stdio.h>

                #define VAL 809

                #define STRINGIFY(x) #x
                #define STR(i) STRINGIFY(i)
                #define SUBSTR(i, n) &(STRINGIFY(i))[n]

                int main (void)
                {
                int whatever = VAL;

                puts(STR(VAL));
                puts(SUBSTR(VAL, 1));

                return 0;
                }


                Output:



                809
                09





                share|improve this answer





















                • Your substr does not count backwards. But it too can be done; you could show it :D
                  – Antti Haapala
                  Nov 7 at 9:04










                • @AnttiHaapala The OP didn't request that, but of course doing so in the pre-processor is trivial :) For your amusement: onlinegdb.com/BJkeNVgTX
                  – Lundin
                  Nov 7 at 9:45










                • So what's wrong with &STRINGIFY(i)[sizeof (STRINGIFY (i)) - n - 1]?
                  – Antti Haapala
                  Nov 7 at 9:53












                • @AnttiHaapala It reads out of bounds of the string literal...? Not sure if I understand what you mean.
                  – Lundin
                  Nov 7 at 9:57










                • #define RIGHT(i, n) &(STRINGIFY(i))[sizeof STRINGIFY(i) - 1 - n] puts(RIGHT(VAL, 2));
                  – Antti Haapala
                  Nov 7 at 10:21

















                up vote
                2
                down vote













                For the specific case of turning "magic numbers" into strings, you can as well do that at compile-time. That is, when you have an integer constant rather than a run-time value:



                #include <stdio.h>

                #define VAL 809

                #define STRINGIFY(x) #x
                #define STR(i) STRINGIFY(i)
                #define SUBSTR(i, n) &(STRINGIFY(i))[n]

                int main (void)
                {
                int whatever = VAL;

                puts(STR(VAL));
                puts(SUBSTR(VAL, 1));

                return 0;
                }


                Output:



                809
                09





                share|improve this answer





















                • Your substr does not count backwards. But it too can be done; you could show it :D
                  – Antti Haapala
                  Nov 7 at 9:04










                • @AnttiHaapala The OP didn't request that, but of course doing so in the pre-processor is trivial :) For your amusement: onlinegdb.com/BJkeNVgTX
                  – Lundin
                  Nov 7 at 9:45










                • So what's wrong with &STRINGIFY(i)[sizeof (STRINGIFY (i)) - n - 1]?
                  – Antti Haapala
                  Nov 7 at 9:53












                • @AnttiHaapala It reads out of bounds of the string literal...? Not sure if I understand what you mean.
                  – Lundin
                  Nov 7 at 9:57










                • #define RIGHT(i, n) &(STRINGIFY(i))[sizeof STRINGIFY(i) - 1 - n] puts(RIGHT(VAL, 2));
                  – Antti Haapala
                  Nov 7 at 10:21















                up vote
                2
                down vote










                up vote
                2
                down vote









                For the specific case of turning "magic numbers" into strings, you can as well do that at compile-time. That is, when you have an integer constant rather than a run-time value:



                #include <stdio.h>

                #define VAL 809

                #define STRINGIFY(x) #x
                #define STR(i) STRINGIFY(i)
                #define SUBSTR(i, n) &(STRINGIFY(i))[n]

                int main (void)
                {
                int whatever = VAL;

                puts(STR(VAL));
                puts(SUBSTR(VAL, 1));

                return 0;
                }


                Output:



                809
                09





                share|improve this answer












                For the specific case of turning "magic numbers" into strings, you can as well do that at compile-time. That is, when you have an integer constant rather than a run-time value:



                #include <stdio.h>

                #define VAL 809

                #define STRINGIFY(x) #x
                #define STR(i) STRINGIFY(i)
                #define SUBSTR(i, n) &(STRINGIFY(i))[n]

                int main (void)
                {
                int whatever = VAL;

                puts(STR(VAL));
                puts(SUBSTR(VAL, 1));

                return 0;
                }


                Output:



                809
                09






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 7 at 8:53









                Lundin

                104k16153257




                104k16153257












                • Your substr does not count backwards. But it too can be done; you could show it :D
                  – Antti Haapala
                  Nov 7 at 9:04










                • @AnttiHaapala The OP didn't request that, but of course doing so in the pre-processor is trivial :) For your amusement: onlinegdb.com/BJkeNVgTX
                  – Lundin
                  Nov 7 at 9:45










                • So what's wrong with &STRINGIFY(i)[sizeof (STRINGIFY (i)) - n - 1]?
                  – Antti Haapala
                  Nov 7 at 9:53












                • @AnttiHaapala It reads out of bounds of the string literal...? Not sure if I understand what you mean.
                  – Lundin
                  Nov 7 at 9:57










                • #define RIGHT(i, n) &(STRINGIFY(i))[sizeof STRINGIFY(i) - 1 - n] puts(RIGHT(VAL, 2));
                  – Antti Haapala
                  Nov 7 at 10:21




















                • Your substr does not count backwards. But it too can be done; you could show it :D
                  – Antti Haapala
                  Nov 7 at 9:04










                • @AnttiHaapala The OP didn't request that, but of course doing so in the pre-processor is trivial :) For your amusement: onlinegdb.com/BJkeNVgTX
                  – Lundin
                  Nov 7 at 9:45










                • So what's wrong with &STRINGIFY(i)[sizeof (STRINGIFY (i)) - n - 1]?
                  – Antti Haapala
                  Nov 7 at 9:53












                • @AnttiHaapala It reads out of bounds of the string literal...? Not sure if I understand what you mean.
                  – Lundin
                  Nov 7 at 9:57










                • #define RIGHT(i, n) &(STRINGIFY(i))[sizeof STRINGIFY(i) - 1 - n] puts(RIGHT(VAL, 2));
                  – Antti Haapala
                  Nov 7 at 10:21


















                Your substr does not count backwards. But it too can be done; you could show it :D
                – Antti Haapala
                Nov 7 at 9:04




                Your substr does not count backwards. But it too can be done; you could show it :D
                – Antti Haapala
                Nov 7 at 9:04












                @AnttiHaapala The OP didn't request that, but of course doing so in the pre-processor is trivial :) For your amusement: onlinegdb.com/BJkeNVgTX
                – Lundin
                Nov 7 at 9:45




                @AnttiHaapala The OP didn't request that, but of course doing so in the pre-processor is trivial :) For your amusement: onlinegdb.com/BJkeNVgTX
                – Lundin
                Nov 7 at 9:45












                So what's wrong with &STRINGIFY(i)[sizeof (STRINGIFY (i)) - n - 1]?
                – Antti Haapala
                Nov 7 at 9:53






                So what's wrong with &STRINGIFY(i)[sizeof (STRINGIFY (i)) - n - 1]?
                – Antti Haapala
                Nov 7 at 9:53














                @AnttiHaapala It reads out of bounds of the string literal...? Not sure if I understand what you mean.
                – Lundin
                Nov 7 at 9:57




                @AnttiHaapala It reads out of bounds of the string literal...? Not sure if I understand what you mean.
                – Lundin
                Nov 7 at 9:57












                #define RIGHT(i, n) &(STRINGIFY(i))[sizeof STRINGIFY(i) - 1 - n] puts(RIGHT(VAL, 2));
                – Antti Haapala
                Nov 7 at 10:21






                #define RIGHT(i, n) &(STRINGIFY(i))[sizeof STRINGIFY(i) - 1 - n] puts(RIGHT(VAL, 2));
                – Antti Haapala
                Nov 7 at 10:21












                up vote
                2
                down vote













                No pointer magic necessary here. Just use plain math (the remainder operator: %), along with some suitable formatting:



                #include <stdio.h>

                int main(void)
                {
                char a[3]; /* 2 characters for any value >= 0 and < 100. So we rely on the 100 below.
                +1 character for the `0`-terminator to make this a C-string*/
                int i = 809;

                assert(i >= 0);

                sprintf(a, "%02d", i % 100);

                puts(a);
                }


                or avoiding magic numbers:



                #include <stdio.h>

                long long power_integer(int base, int x)
                {
                if (0 == x)
                {
                return 1;
                }

                return base * power_integer(x - 1);
                }

                #define CUTOFF_BASE (10)
                #define CUTOFF_DIGITS (2)

                int main(void)
                {
                char a[3];
                char f[8]; /* To hold "%01lld" to "%019lld".
                (A 64 bit integer in decimal uses max 19 digits) */

                int i = 809;

                assert(i >= 0);

                sprintf(f, "%%0%dlld*, CUTOFF_DIGITS);
                sprintf(a, f, i % power_integer(CUTOFF_BASE, CUTOFF_DIGITS));

                puts(a);
                }


                Output would be:



                09





                share|improve this answer



























                  up vote
                  2
                  down vote













                  No pointer magic necessary here. Just use plain math (the remainder operator: %), along with some suitable formatting:



                  #include <stdio.h>

                  int main(void)
                  {
                  char a[3]; /* 2 characters for any value >= 0 and < 100. So we rely on the 100 below.
                  +1 character for the `0`-terminator to make this a C-string*/
                  int i = 809;

                  assert(i >= 0);

                  sprintf(a, "%02d", i % 100);

                  puts(a);
                  }


                  or avoiding magic numbers:



                  #include <stdio.h>

                  long long power_integer(int base, int x)
                  {
                  if (0 == x)
                  {
                  return 1;
                  }

                  return base * power_integer(x - 1);
                  }

                  #define CUTOFF_BASE (10)
                  #define CUTOFF_DIGITS (2)

                  int main(void)
                  {
                  char a[3];
                  char f[8]; /* To hold "%01lld" to "%019lld".
                  (A 64 bit integer in decimal uses max 19 digits) */

                  int i = 809;

                  assert(i >= 0);

                  sprintf(f, "%%0%dlld*, CUTOFF_DIGITS);
                  sprintf(a, f, i % power_integer(CUTOFF_BASE, CUTOFF_DIGITS));

                  puts(a);
                  }


                  Output would be:



                  09





                  share|improve this answer

























                    up vote
                    2
                    down vote










                    up vote
                    2
                    down vote









                    No pointer magic necessary here. Just use plain math (the remainder operator: %), along with some suitable formatting:



                    #include <stdio.h>

                    int main(void)
                    {
                    char a[3]; /* 2 characters for any value >= 0 and < 100. So we rely on the 100 below.
                    +1 character for the `0`-terminator to make this a C-string*/
                    int i = 809;

                    assert(i >= 0);

                    sprintf(a, "%02d", i % 100);

                    puts(a);
                    }


                    or avoiding magic numbers:



                    #include <stdio.h>

                    long long power_integer(int base, int x)
                    {
                    if (0 == x)
                    {
                    return 1;
                    }

                    return base * power_integer(x - 1);
                    }

                    #define CUTOFF_BASE (10)
                    #define CUTOFF_DIGITS (2)

                    int main(void)
                    {
                    char a[3];
                    char f[8]; /* To hold "%01lld" to "%019lld".
                    (A 64 bit integer in decimal uses max 19 digits) */

                    int i = 809;

                    assert(i >= 0);

                    sprintf(f, "%%0%dlld*, CUTOFF_DIGITS);
                    sprintf(a, f, i % power_integer(CUTOFF_BASE, CUTOFF_DIGITS));

                    puts(a);
                    }


                    Output would be:



                    09





                    share|improve this answer














                    No pointer magic necessary here. Just use plain math (the remainder operator: %), along with some suitable formatting:



                    #include <stdio.h>

                    int main(void)
                    {
                    char a[3]; /* 2 characters for any value >= 0 and < 100. So we rely on the 100 below.
                    +1 character for the `0`-terminator to make this a C-string*/
                    int i = 809;

                    assert(i >= 0);

                    sprintf(a, "%02d", i % 100);

                    puts(a);
                    }


                    or avoiding magic numbers:



                    #include <stdio.h>

                    long long power_integer(int base, int x)
                    {
                    if (0 == x)
                    {
                    return 1;
                    }

                    return base * power_integer(x - 1);
                    }

                    #define CUTOFF_BASE (10)
                    #define CUTOFF_DIGITS (2)

                    int main(void)
                    {
                    char a[3];
                    char f[8]; /* To hold "%01lld" to "%019lld".
                    (A 64 bit integer in decimal uses max 19 digits) */

                    int i = 809;

                    assert(i >= 0);

                    sprintf(f, "%%0%dlld*, CUTOFF_DIGITS);
                    sprintf(a, f, i % power_integer(CUTOFF_BASE, CUTOFF_DIGITS));

                    puts(a);
                    }


                    Output would be:



                    09






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 8 at 6:48

























                    answered Nov 7 at 8:32









                    alk

                    57.5k758165




                    57.5k758165






















                        up vote
                        1
                        down vote













                        You could try something like this:



                        #include <stdio.h>
                        #include <string.h>
                        int main(int argc, char **argv){
                        int myInt = 809;
                        char buf[16]; // buffer big enough to hold the string representation
                        sprintf(buf, "%d", myInt); // write the string to the buffer
                        char* myStr = &buf[strlen(buf) - 2]; // set a pointer to the second last position
                        printf("myStr is %sn", myStr);
                        return 0;
                        }





                        share|improve this answer



























                          up vote
                          1
                          down vote













                          You could try something like this:



                          #include <stdio.h>
                          #include <string.h>
                          int main(int argc, char **argv){
                          int myInt = 809;
                          char buf[16]; // buffer big enough to hold the string representation
                          sprintf(buf, "%d", myInt); // write the string to the buffer
                          char* myStr = &buf[strlen(buf) - 2]; // set a pointer to the second last position
                          printf("myStr is %sn", myStr);
                          return 0;
                          }





                          share|improve this answer

























                            up vote
                            1
                            down vote










                            up vote
                            1
                            down vote









                            You could try something like this:



                            #include <stdio.h>
                            #include <string.h>
                            int main(int argc, char **argv){
                            int myInt = 809;
                            char buf[16]; // buffer big enough to hold the string representation
                            sprintf(buf, "%d", myInt); // write the string to the buffer
                            char* myStr = &buf[strlen(buf) - 2]; // set a pointer to the second last position
                            printf("myStr is %sn", myStr);
                            return 0;
                            }





                            share|improve this answer














                            You could try something like this:



                            #include <stdio.h>
                            #include <string.h>
                            int main(int argc, char **argv){
                            int myInt = 809;
                            char buf[16]; // buffer big enough to hold the string representation
                            sprintf(buf, "%d", myInt); // write the string to the buffer
                            char* myStr = &buf[strlen(buf) - 2]; // set a pointer to the second last position
                            printf("myStr is %sn", myStr);
                            return 0;
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 7 at 8:03









                            Jonathan Leffler

                            553k876581009




                            553k876581009










                            answered Nov 7 at 7:55









                            Blaze

                            2,5721524




                            2,5721524






























                                 

                                draft saved


                                draft discarded



















































                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53185370%2freturn-two-last-digits-of-an-integer-as-string-in-c%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest




















































































                                這個網誌中的熱門文章

                                Academy of Television Arts & Sciences

                                L'Équipe

                                1995 France bombings