Convert part of a string to int in one command in C












1















I have a long string where I know the location of start and end of an integer. I want to extract the integer and store it in a variable. This is how I can do it now.



//MY_STRING, INT_START, INT_END are the string, start 
//position of the int and end position respectively.
char * temp;
strncpy(temp, MY_STRING+INT_START, INT_END-INT_START);
int n = atoi(temp);


The question is can I do this in one line, instead of using a temp string?










share|improve this question


















  • 3





    Why "one line"..specifically?

    – Sourav Ghosh
    Nov 23 '18 at 8:02











  • Maybe atoi can automatically detect the end of a number: atoi(MY_STRING+INT_START). In online GDB it works.

    – A.R.C.
    Nov 23 '18 at 8:03






  • 1





    Be aware that strncpy is not a safer version of strcpy. You may end up with a non NUL terminated string. Read carefully the strncpy documentation

    – Jabberwocky
    Nov 23 '18 at 8:13






  • 2





    If you really need a one liner that does error checking, you can simply write your own parsing functions, and even differentiate different types and formats (parse_u32, parse_float, parse_hex16). Then you'll have a one liner which does what it's supposed to do.

    – Groo
    Nov 23 '18 at 8:14
















1















I have a long string where I know the location of start and end of an integer. I want to extract the integer and store it in a variable. This is how I can do it now.



//MY_STRING, INT_START, INT_END are the string, start 
//position of the int and end position respectively.
char * temp;
strncpy(temp, MY_STRING+INT_START, INT_END-INT_START);
int n = atoi(temp);


The question is can I do this in one line, instead of using a temp string?










share|improve this question


















  • 3





    Why "one line"..specifically?

    – Sourav Ghosh
    Nov 23 '18 at 8:02











  • Maybe atoi can automatically detect the end of a number: atoi(MY_STRING+INT_START). In online GDB it works.

    – A.R.C.
    Nov 23 '18 at 8:03






  • 1





    Be aware that strncpy is not a safer version of strcpy. You may end up with a non NUL terminated string. Read carefully the strncpy documentation

    – Jabberwocky
    Nov 23 '18 at 8:13






  • 2





    If you really need a one liner that does error checking, you can simply write your own parsing functions, and even differentiate different types and formats (parse_u32, parse_float, parse_hex16). Then you'll have a one liner which does what it's supposed to do.

    – Groo
    Nov 23 '18 at 8:14














1












1








1


0






I have a long string where I know the location of start and end of an integer. I want to extract the integer and store it in a variable. This is how I can do it now.



//MY_STRING, INT_START, INT_END are the string, start 
//position of the int and end position respectively.
char * temp;
strncpy(temp, MY_STRING+INT_START, INT_END-INT_START);
int n = atoi(temp);


The question is can I do this in one line, instead of using a temp string?










share|improve this question














I have a long string where I know the location of start and end of an integer. I want to extract the integer and store it in a variable. This is how I can do it now.



//MY_STRING, INT_START, INT_END are the string, start 
//position of the int and end position respectively.
char * temp;
strncpy(temp, MY_STRING+INT_START, INT_END-INT_START);
int n = atoi(temp);


The question is can I do this in one line, instead of using a temp string?







c string parsing






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 7:58









user38161user38161

82




82








  • 3





    Why "one line"..specifically?

    – Sourav Ghosh
    Nov 23 '18 at 8:02











  • Maybe atoi can automatically detect the end of a number: atoi(MY_STRING+INT_START). In online GDB it works.

    – A.R.C.
    Nov 23 '18 at 8:03






  • 1





    Be aware that strncpy is not a safer version of strcpy. You may end up with a non NUL terminated string. Read carefully the strncpy documentation

    – Jabberwocky
    Nov 23 '18 at 8:13






  • 2





    If you really need a one liner that does error checking, you can simply write your own parsing functions, and even differentiate different types and formats (parse_u32, parse_float, parse_hex16). Then you'll have a one liner which does what it's supposed to do.

    – Groo
    Nov 23 '18 at 8:14














  • 3





    Why "one line"..specifically?

    – Sourav Ghosh
    Nov 23 '18 at 8:02











  • Maybe atoi can automatically detect the end of a number: atoi(MY_STRING+INT_START). In online GDB it works.

    – A.R.C.
    Nov 23 '18 at 8:03






  • 1





    Be aware that strncpy is not a safer version of strcpy. You may end up with a non NUL terminated string. Read carefully the strncpy documentation

    – Jabberwocky
    Nov 23 '18 at 8:13






  • 2





    If you really need a one liner that does error checking, you can simply write your own parsing functions, and even differentiate different types and formats (parse_u32, parse_float, parse_hex16). Then you'll have a one liner which does what it's supposed to do.

    – Groo
    Nov 23 '18 at 8:14








3




3





Why "one line"..specifically?

– Sourav Ghosh
Nov 23 '18 at 8:02





Why "one line"..specifically?

– Sourav Ghosh
Nov 23 '18 at 8:02













Maybe atoi can automatically detect the end of a number: atoi(MY_STRING+INT_START). In online GDB it works.

– A.R.C.
Nov 23 '18 at 8:03





Maybe atoi can automatically detect the end of a number: atoi(MY_STRING+INT_START). In online GDB it works.

– A.R.C.
Nov 23 '18 at 8:03




1




1





Be aware that strncpy is not a safer version of strcpy. You may end up with a non NUL terminated string. Read carefully the strncpy documentation

– Jabberwocky
Nov 23 '18 at 8:13





Be aware that strncpy is not a safer version of strcpy. You may end up with a non NUL terminated string. Read carefully the strncpy documentation

– Jabberwocky
Nov 23 '18 at 8:13




2




2





If you really need a one liner that does error checking, you can simply write your own parsing functions, and even differentiate different types and formats (parse_u32, parse_float, parse_hex16). Then you'll have a one liner which does what it's supposed to do.

– Groo
Nov 23 '18 at 8:14





If you really need a one liner that does error checking, you can simply write your own parsing functions, and even differentiate different types and formats (parse_u32, parse_float, parse_hex16). Then you'll have a one liner which does what it's supposed to do.

– Groo
Nov 23 '18 at 8:14












2 Answers
2






active

oldest

votes


















3















can I do this in one line, instead of using a temp string?




Use sscanf() for a quick dirty no-temp.



int n;
// v--- scan width limit
// | v---------------v
if (sscanf(MY_STRING + INT_START, "%*d", INT_END-INT_START, &n) == 1) {
puts("Success");
}


Better code would consider trouble with overflow.





OP's code is no good as temp is not certain to point to a string. It may lack a null character.



strncpy(temp, MY_STRING+INT_START, INT_END-INT_START);
int n = atoi(temp); // bad





share|improve this answer





















  • 1





    Well, but this is 4 lines scnr

    – moooeeeep
    Nov 23 '18 at 8:04






  • 1





    @moooeeeep but I guess the requirement was to avoid the temp string...so this should be okay.

    – Sourav Ghosh
    Nov 23 '18 at 8:05











  • @moooeeeep At least the conversion happens in one line/command.

    – chux
    Nov 23 '18 at 8:10











  • INT_END and INT_START are supposed to check for null character. They come from a token generator.

    – user38161
    Nov 23 '18 at 8:26



















2














No, you cannot do it in one line and the number of source code lines is most often an irrelevant metric. The only things that matter are safety, readability and performance. strncpy and atoi are both unsafe functions.



The correct way to do this is however quite similar:



int strn_to_int (const char* src, size_t n)
{
char str [LARGE_ENOUGH];
memcpy(str, src, n);
str[n] = '';
return strtol(str, NULL, 10);
}

...

int n = strn_to_int (&MY_STRING[INT_START], INT_END-INT_START);





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',
    autoActivateHeartbeat: false,
    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%2f53442679%2fconvert-part-of-a-string-to-int-in-one-command-in-c%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3















    can I do this in one line, instead of using a temp string?




    Use sscanf() for a quick dirty no-temp.



    int n;
    // v--- scan width limit
    // | v---------------v
    if (sscanf(MY_STRING + INT_START, "%*d", INT_END-INT_START, &n) == 1) {
    puts("Success");
    }


    Better code would consider trouble with overflow.





    OP's code is no good as temp is not certain to point to a string. It may lack a null character.



    strncpy(temp, MY_STRING+INT_START, INT_END-INT_START);
    int n = atoi(temp); // bad





    share|improve this answer





















    • 1





      Well, but this is 4 lines scnr

      – moooeeeep
      Nov 23 '18 at 8:04






    • 1





      @moooeeeep but I guess the requirement was to avoid the temp string...so this should be okay.

      – Sourav Ghosh
      Nov 23 '18 at 8:05











    • @moooeeeep At least the conversion happens in one line/command.

      – chux
      Nov 23 '18 at 8:10











    • INT_END and INT_START are supposed to check for null character. They come from a token generator.

      – user38161
      Nov 23 '18 at 8:26
















    3















    can I do this in one line, instead of using a temp string?




    Use sscanf() for a quick dirty no-temp.



    int n;
    // v--- scan width limit
    // | v---------------v
    if (sscanf(MY_STRING + INT_START, "%*d", INT_END-INT_START, &n) == 1) {
    puts("Success");
    }


    Better code would consider trouble with overflow.





    OP's code is no good as temp is not certain to point to a string. It may lack a null character.



    strncpy(temp, MY_STRING+INT_START, INT_END-INT_START);
    int n = atoi(temp); // bad





    share|improve this answer





















    • 1





      Well, but this is 4 lines scnr

      – moooeeeep
      Nov 23 '18 at 8:04






    • 1





      @moooeeeep but I guess the requirement was to avoid the temp string...so this should be okay.

      – Sourav Ghosh
      Nov 23 '18 at 8:05











    • @moooeeeep At least the conversion happens in one line/command.

      – chux
      Nov 23 '18 at 8:10











    • INT_END and INT_START are supposed to check for null character. They come from a token generator.

      – user38161
      Nov 23 '18 at 8:26














    3












    3








    3








    can I do this in one line, instead of using a temp string?




    Use sscanf() for a quick dirty no-temp.



    int n;
    // v--- scan width limit
    // | v---------------v
    if (sscanf(MY_STRING + INT_START, "%*d", INT_END-INT_START, &n) == 1) {
    puts("Success");
    }


    Better code would consider trouble with overflow.





    OP's code is no good as temp is not certain to point to a string. It may lack a null character.



    strncpy(temp, MY_STRING+INT_START, INT_END-INT_START);
    int n = atoi(temp); // bad





    share|improve this answer
















    can I do this in one line, instead of using a temp string?




    Use sscanf() for a quick dirty no-temp.



    int n;
    // v--- scan width limit
    // | v---------------v
    if (sscanf(MY_STRING + INT_START, "%*d", INT_END-INT_START, &n) == 1) {
    puts("Success");
    }


    Better code would consider trouble with overflow.





    OP's code is no good as temp is not certain to point to a string. It may lack a null character.



    strncpy(temp, MY_STRING+INT_START, INT_END-INT_START);
    int n = atoi(temp); // bad






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 23 '18 at 8:07

























    answered Nov 23 '18 at 8:03









    chuxchux

    82.8k872149




    82.8k872149








    • 1





      Well, but this is 4 lines scnr

      – moooeeeep
      Nov 23 '18 at 8:04






    • 1





      @moooeeeep but I guess the requirement was to avoid the temp string...so this should be okay.

      – Sourav Ghosh
      Nov 23 '18 at 8:05











    • @moooeeeep At least the conversion happens in one line/command.

      – chux
      Nov 23 '18 at 8:10











    • INT_END and INT_START are supposed to check for null character. They come from a token generator.

      – user38161
      Nov 23 '18 at 8:26














    • 1





      Well, but this is 4 lines scnr

      – moooeeeep
      Nov 23 '18 at 8:04






    • 1





      @moooeeeep but I guess the requirement was to avoid the temp string...so this should be okay.

      – Sourav Ghosh
      Nov 23 '18 at 8:05











    • @moooeeeep At least the conversion happens in one line/command.

      – chux
      Nov 23 '18 at 8:10











    • INT_END and INT_START are supposed to check for null character. They come from a token generator.

      – user38161
      Nov 23 '18 at 8:26








    1




    1





    Well, but this is 4 lines scnr

    – moooeeeep
    Nov 23 '18 at 8:04





    Well, but this is 4 lines scnr

    – moooeeeep
    Nov 23 '18 at 8:04




    1




    1





    @moooeeeep but I guess the requirement was to avoid the temp string...so this should be okay.

    – Sourav Ghosh
    Nov 23 '18 at 8:05





    @moooeeeep but I guess the requirement was to avoid the temp string...so this should be okay.

    – Sourav Ghosh
    Nov 23 '18 at 8:05













    @moooeeeep At least the conversion happens in one line/command.

    – chux
    Nov 23 '18 at 8:10





    @moooeeeep At least the conversion happens in one line/command.

    – chux
    Nov 23 '18 at 8:10













    INT_END and INT_START are supposed to check for null character. They come from a token generator.

    – user38161
    Nov 23 '18 at 8:26





    INT_END and INT_START are supposed to check for null character. They come from a token generator.

    – user38161
    Nov 23 '18 at 8:26













    2














    No, you cannot do it in one line and the number of source code lines is most often an irrelevant metric. The only things that matter are safety, readability and performance. strncpy and atoi are both unsafe functions.



    The correct way to do this is however quite similar:



    int strn_to_int (const char* src, size_t n)
    {
    char str [LARGE_ENOUGH];
    memcpy(str, src, n);
    str[n] = '';
    return strtol(str, NULL, 10);
    }

    ...

    int n = strn_to_int (&MY_STRING[INT_START], INT_END-INT_START);





    share|improve this answer






























      2














      No, you cannot do it in one line and the number of source code lines is most often an irrelevant metric. The only things that matter are safety, readability and performance. strncpy and atoi are both unsafe functions.



      The correct way to do this is however quite similar:



      int strn_to_int (const char* src, size_t n)
      {
      char str [LARGE_ENOUGH];
      memcpy(str, src, n);
      str[n] = '';
      return strtol(str, NULL, 10);
      }

      ...

      int n = strn_to_int (&MY_STRING[INT_START], INT_END-INT_START);





      share|improve this answer




























        2












        2








        2







        No, you cannot do it in one line and the number of source code lines is most often an irrelevant metric. The only things that matter are safety, readability and performance. strncpy and atoi are both unsafe functions.



        The correct way to do this is however quite similar:



        int strn_to_int (const char* src, size_t n)
        {
        char str [LARGE_ENOUGH];
        memcpy(str, src, n);
        str[n] = '';
        return strtol(str, NULL, 10);
        }

        ...

        int n = strn_to_int (&MY_STRING[INT_START], INT_END-INT_START);





        share|improve this answer















        No, you cannot do it in one line and the number of source code lines is most often an irrelevant metric. The only things that matter are safety, readability and performance. strncpy and atoi are both unsafe functions.



        The correct way to do this is however quite similar:



        int strn_to_int (const char* src, size_t n)
        {
        char str [LARGE_ENOUGH];
        memcpy(str, src, n);
        str[n] = '';
        return strtol(str, NULL, 10);
        }

        ...

        int n = strn_to_int (&MY_STRING[INT_START], INT_END-INT_START);






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 23 '18 at 10:06

























        answered Nov 23 '18 at 8:41









        LundinLundin

        109k17160265




        109k17160265






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53442679%2fconvert-part-of-a-string-to-int-in-one-command-in-c%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Wiesbaden

            Marschland

            Dieringhausen