Convert a string to an int with negative numbers









up vote
2
down vote

favorite












I need to write a function in C that converts a string (data pointed to by a char *) to an int. I've already done this successfully with this code:



int charTOint(char * c) 
char p = *c;
int ergebnis = 0;

while (p)
ergebnis = ergebnis * 10 + (p - '0');
c++;
p = *c;


return ergebnis;



My problem now is, that I need it to also work with negative numbers / char arrays starting with a '-'.



I know that I have to check, whether the first char is a '-', but I'm stuck after that.



I know the '-' is the 45th character of the ASCII table, but I somehow can't think of a way to make it work.










share|improve this question



























    up vote
    2
    down vote

    favorite












    I need to write a function in C that converts a string (data pointed to by a char *) to an int. I've already done this successfully with this code:



    int charTOint(char * c) 
    char p = *c;
    int ergebnis = 0;

    while (p)
    ergebnis = ergebnis * 10 + (p - '0');
    c++;
    p = *c;


    return ergebnis;



    My problem now is, that I need it to also work with negative numbers / char arrays starting with a '-'.



    I know that I have to check, whether the first char is a '-', but I'm stuck after that.



    I know the '-' is the 45th character of the ASCII table, but I somehow can't think of a way to make it work.










    share|improve this question

























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      I need to write a function in C that converts a string (data pointed to by a char *) to an int. I've already done this successfully with this code:



      int charTOint(char * c) 
      char p = *c;
      int ergebnis = 0;

      while (p)
      ergebnis = ergebnis * 10 + (p - '0');
      c++;
      p = *c;


      return ergebnis;



      My problem now is, that I need it to also work with negative numbers / char arrays starting with a '-'.



      I know that I have to check, whether the first char is a '-', but I'm stuck after that.



      I know the '-' is the 45th character of the ASCII table, but I somehow can't think of a way to make it work.










      share|improve this question















      I need to write a function in C that converts a string (data pointed to by a char *) to an int. I've already done this successfully with this code:



      int charTOint(char * c) 
      char p = *c;
      int ergebnis = 0;

      while (p)
      ergebnis = ergebnis * 10 + (p - '0');
      c++;
      p = *c;


      return ergebnis;



      My problem now is, that I need it to also work with negative numbers / char arrays starting with a '-'.



      I know that I have to check, whether the first char is a '-', but I'm stuck after that.



      I know the '-' is the 45th character of the ASCII table, but I somehow can't think of a way to make it work.







      c char int






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 11 at 16:27









      chux

      79.6k869146




      79.6k869146










      asked Nov 11 at 13:15









      Halsi

      214




      214






















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          2
          down vote



          accepted











          I've already done this successfully (with positive) with this code:




          Good. An important insight is to build on success.



          As int charTOint(char * c) { works well with positive values, perhaps re-write it using unsigned. We get more range as UINT_MAX is typically greater than INT_MAX.



          unsigned charTOunsigned(const char * c) 
          char p = *c;
          unsigned ergebnis = 0;
          while (p)
          ergebnis = ergebnis * 10 + (p - '0');
          c++;
          p = *c;

          return ergebnis;




          I need it to also work with negative numbers / char arrays starting with a '-'.




          Now armed with charTOunsigned(), use that variation of good existing code to re-make a int charTOint() that meets the additional goal. With the usual extra positive range of charTOunsigned(), int charTOint() will readily handle a string that converts to INT_MIN.



          int charTOint(const char * c) 
          return (*c == '-') ? -charTOunsigned(c+ 1) : charTOunsigned(c);




          Certainly one could code a stand-alone charTOint(), yet I wanted to emphasize code re-use. That makes for a productive coder.






          share|improve this answer





























            up vote
            1
            down vote













            Another variable could be added to recognize the sign. Then multiply by the sign variable.

            A check should be added to confirm that only digits are processed. If the input was 123abc, this will stop after 123



            int charTOint(char * c) 
            char p = *c;
            int ergebnis = 0;
            int sign = 1;

            if ( '-' == *c


            EDIT 3:



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

            int charTOint(char *c, int *number)
            char p = *c;
            int sign = 1;
            int divmax = INT_MAX / 10;
            int divmin = INT_MIN / 10;

            *number = 0;
            while ( ' ' == *c

            int main ( void)
            char text[100] = "";
            int value = 0;

            do
            printf ( "enter an integer or enter donen");
            if ( fgets ( text, sizeof text, stdin))
            text[strcspn ( text, "n")] = 0;
            if ( charTOint ( text, &value))
            printf ( "value = %dn", value);

            else
            printf ( "input [%s]n", text);


            else
            fprintf ( stderr, "fgets EOFn");
            return 0;

            while ( strcmp ( text, "done"));
            return 0;






            share|improve this answer






















            • The works well expect for the corner case when the result should be INT_MIN as ergebnis = ergebnis * 10 + p; overflows. A successful result depends on undefined behavior.
              – chux
              Nov 11 at 16:35










            • Try charTOint("2147483639")
              – chux
              Nov 12 at 0:31










            • Implementation of atoi() may be a useful read.
              – chux
              Nov 12 at 0:49










            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%2f53249100%2fconvert-a-string-to-an-int-with-negative-numbers%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








            up vote
            2
            down vote



            accepted











            I've already done this successfully (with positive) with this code:




            Good. An important insight is to build on success.



            As int charTOint(char * c) { works well with positive values, perhaps re-write it using unsigned. We get more range as UINT_MAX is typically greater than INT_MAX.



            unsigned charTOunsigned(const char * c) 
            char p = *c;
            unsigned ergebnis = 0;
            while (p)
            ergebnis = ergebnis * 10 + (p - '0');
            c++;
            p = *c;

            return ergebnis;




            I need it to also work with negative numbers / char arrays starting with a '-'.




            Now armed with charTOunsigned(), use that variation of good existing code to re-make a int charTOint() that meets the additional goal. With the usual extra positive range of charTOunsigned(), int charTOint() will readily handle a string that converts to INT_MIN.



            int charTOint(const char * c) 
            return (*c == '-') ? -charTOunsigned(c+ 1) : charTOunsigned(c);




            Certainly one could code a stand-alone charTOint(), yet I wanted to emphasize code re-use. That makes for a productive coder.






            share|improve this answer


























              up vote
              2
              down vote



              accepted











              I've already done this successfully (with positive) with this code:




              Good. An important insight is to build on success.



              As int charTOint(char * c) { works well with positive values, perhaps re-write it using unsigned. We get more range as UINT_MAX is typically greater than INT_MAX.



              unsigned charTOunsigned(const char * c) 
              char p = *c;
              unsigned ergebnis = 0;
              while (p)
              ergebnis = ergebnis * 10 + (p - '0');
              c++;
              p = *c;

              return ergebnis;




              I need it to also work with negative numbers / char arrays starting with a '-'.




              Now armed with charTOunsigned(), use that variation of good existing code to re-make a int charTOint() that meets the additional goal. With the usual extra positive range of charTOunsigned(), int charTOint() will readily handle a string that converts to INT_MIN.



              int charTOint(const char * c) 
              return (*c == '-') ? -charTOunsigned(c+ 1) : charTOunsigned(c);




              Certainly one could code a stand-alone charTOint(), yet I wanted to emphasize code re-use. That makes for a productive coder.






              share|improve this answer
























                up vote
                2
                down vote



                accepted







                up vote
                2
                down vote



                accepted







                I've already done this successfully (with positive) with this code:




                Good. An important insight is to build on success.



                As int charTOint(char * c) { works well with positive values, perhaps re-write it using unsigned. We get more range as UINT_MAX is typically greater than INT_MAX.



                unsigned charTOunsigned(const char * c) 
                char p = *c;
                unsigned ergebnis = 0;
                while (p)
                ergebnis = ergebnis * 10 + (p - '0');
                c++;
                p = *c;

                return ergebnis;




                I need it to also work with negative numbers / char arrays starting with a '-'.




                Now armed with charTOunsigned(), use that variation of good existing code to re-make a int charTOint() that meets the additional goal. With the usual extra positive range of charTOunsigned(), int charTOint() will readily handle a string that converts to INT_MIN.



                int charTOint(const char * c) 
                return (*c == '-') ? -charTOunsigned(c+ 1) : charTOunsigned(c);




                Certainly one could code a stand-alone charTOint(), yet I wanted to emphasize code re-use. That makes for a productive coder.






                share|improve this answer















                I've already done this successfully (with positive) with this code:




                Good. An important insight is to build on success.



                As int charTOint(char * c) { works well with positive values, perhaps re-write it using unsigned. We get more range as UINT_MAX is typically greater than INT_MAX.



                unsigned charTOunsigned(const char * c) 
                char p = *c;
                unsigned ergebnis = 0;
                while (p)
                ergebnis = ergebnis * 10 + (p - '0');
                c++;
                p = *c;

                return ergebnis;




                I need it to also work with negative numbers / char arrays starting with a '-'.




                Now armed with charTOunsigned(), use that variation of good existing code to re-make a int charTOint() that meets the additional goal. With the usual extra positive range of charTOunsigned(), int charTOint() will readily handle a string that converts to INT_MIN.



                int charTOint(const char * c) 
                return (*c == '-') ? -charTOunsigned(c+ 1) : charTOunsigned(c);




                Certainly one could code a stand-alone charTOint(), yet I wanted to emphasize code re-use. That makes for a productive coder.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 12 at 15:31

























                answered Nov 11 at 19:05









                chux

                79.6k869146




                79.6k869146






















                    up vote
                    1
                    down vote













                    Another variable could be added to recognize the sign. Then multiply by the sign variable.

                    A check should be added to confirm that only digits are processed. If the input was 123abc, this will stop after 123



                    int charTOint(char * c) 
                    char p = *c;
                    int ergebnis = 0;
                    int sign = 1;

                    if ( '-' == *c


                    EDIT 3:



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

                    int charTOint(char *c, int *number)
                    char p = *c;
                    int sign = 1;
                    int divmax = INT_MAX / 10;
                    int divmin = INT_MIN / 10;

                    *number = 0;
                    while ( ' ' == *c

                    int main ( void)
                    char text[100] = "";
                    int value = 0;

                    do
                    printf ( "enter an integer or enter donen");
                    if ( fgets ( text, sizeof text, stdin))
                    text[strcspn ( text, "n")] = 0;
                    if ( charTOint ( text, &value))
                    printf ( "value = %dn", value);

                    else
                    printf ( "input [%s]n", text);


                    else
                    fprintf ( stderr, "fgets EOFn");
                    return 0;

                    while ( strcmp ( text, "done"));
                    return 0;






                    share|improve this answer






















                    • The works well expect for the corner case when the result should be INT_MIN as ergebnis = ergebnis * 10 + p; overflows. A successful result depends on undefined behavior.
                      – chux
                      Nov 11 at 16:35










                    • Try charTOint("2147483639")
                      – chux
                      Nov 12 at 0:31










                    • Implementation of atoi() may be a useful read.
                      – chux
                      Nov 12 at 0:49














                    up vote
                    1
                    down vote













                    Another variable could be added to recognize the sign. Then multiply by the sign variable.

                    A check should be added to confirm that only digits are processed. If the input was 123abc, this will stop after 123



                    int charTOint(char * c) 
                    char p = *c;
                    int ergebnis = 0;
                    int sign = 1;

                    if ( '-' == *c


                    EDIT 3:



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

                    int charTOint(char *c, int *number)
                    char p = *c;
                    int sign = 1;
                    int divmax = INT_MAX / 10;
                    int divmin = INT_MIN / 10;

                    *number = 0;
                    while ( ' ' == *c

                    int main ( void)
                    char text[100] = "";
                    int value = 0;

                    do
                    printf ( "enter an integer or enter donen");
                    if ( fgets ( text, sizeof text, stdin))
                    text[strcspn ( text, "n")] = 0;
                    if ( charTOint ( text, &value))
                    printf ( "value = %dn", value);

                    else
                    printf ( "input [%s]n", text);


                    else
                    fprintf ( stderr, "fgets EOFn");
                    return 0;

                    while ( strcmp ( text, "done"));
                    return 0;






                    share|improve this answer






















                    • The works well expect for the corner case when the result should be INT_MIN as ergebnis = ergebnis * 10 + p; overflows. A successful result depends on undefined behavior.
                      – chux
                      Nov 11 at 16:35










                    • Try charTOint("2147483639")
                      – chux
                      Nov 12 at 0:31










                    • Implementation of atoi() may be a useful read.
                      – chux
                      Nov 12 at 0:49












                    up vote
                    1
                    down vote










                    up vote
                    1
                    down vote









                    Another variable could be added to recognize the sign. Then multiply by the sign variable.

                    A check should be added to confirm that only digits are processed. If the input was 123abc, this will stop after 123



                    int charTOint(char * c) 
                    char p = *c;
                    int ergebnis = 0;
                    int sign = 1;

                    if ( '-' == *c


                    EDIT 3:



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

                    int charTOint(char *c, int *number)
                    char p = *c;
                    int sign = 1;
                    int divmax = INT_MAX / 10;
                    int divmin = INT_MIN / 10;

                    *number = 0;
                    while ( ' ' == *c

                    int main ( void)
                    char text[100] = "";
                    int value = 0;

                    do
                    printf ( "enter an integer or enter donen");
                    if ( fgets ( text, sizeof text, stdin))
                    text[strcspn ( text, "n")] = 0;
                    if ( charTOint ( text, &value))
                    printf ( "value = %dn", value);

                    else
                    printf ( "input [%s]n", text);


                    else
                    fprintf ( stderr, "fgets EOFn");
                    return 0;

                    while ( strcmp ( text, "done"));
                    return 0;






                    share|improve this answer














                    Another variable could be added to recognize the sign. Then multiply by the sign variable.

                    A check should be added to confirm that only digits are processed. If the input was 123abc, this will stop after 123



                    int charTOint(char * c) 
                    char p = *c;
                    int ergebnis = 0;
                    int sign = 1;

                    if ( '-' == *c


                    EDIT 3:



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

                    int charTOint(char *c, int *number)
                    char p = *c;
                    int sign = 1;
                    int divmax = INT_MAX / 10;
                    int divmin = INT_MIN / 10;

                    *number = 0;
                    while ( ' ' == *c

                    int main ( void)
                    char text[100] = "";
                    int value = 0;

                    do
                    printf ( "enter an integer or enter donen");
                    if ( fgets ( text, sizeof text, stdin))
                    text[strcspn ( text, "n")] = 0;
                    if ( charTOint ( text, &value))
                    printf ( "value = %dn", value);

                    else
                    printf ( "input [%s]n", text);


                    else
                    fprintf ( stderr, "fgets EOFn");
                    return 0;

                    while ( strcmp ( text, "done"));
                    return 0;







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 13 at 12:28

























                    answered Nov 11 at 13:50









                    user3121023

                    5,41741113




                    5,41741113











                    • The works well expect for the corner case when the result should be INT_MIN as ergebnis = ergebnis * 10 + p; overflows. A successful result depends on undefined behavior.
                      – chux
                      Nov 11 at 16:35










                    • Try charTOint("2147483639")
                      – chux
                      Nov 12 at 0:31










                    • Implementation of atoi() may be a useful read.
                      – chux
                      Nov 12 at 0:49
















                    • The works well expect for the corner case when the result should be INT_MIN as ergebnis = ergebnis * 10 + p; overflows. A successful result depends on undefined behavior.
                      – chux
                      Nov 11 at 16:35










                    • Try charTOint("2147483639")
                      – chux
                      Nov 12 at 0:31










                    • Implementation of atoi() may be a useful read.
                      – chux
                      Nov 12 at 0:49















                    The works well expect for the corner case when the result should be INT_MIN as ergebnis = ergebnis * 10 + p; overflows. A successful result depends on undefined behavior.
                    – chux
                    Nov 11 at 16:35




                    The works well expect for the corner case when the result should be INT_MIN as ergebnis = ergebnis * 10 + p; overflows. A successful result depends on undefined behavior.
                    – chux
                    Nov 11 at 16:35












                    Try charTOint("2147483639")
                    – chux
                    Nov 12 at 0:31




                    Try charTOint("2147483639")
                    – chux
                    Nov 12 at 0:31












                    Implementation of atoi() may be a useful read.
                    – chux
                    Nov 12 at 0:49




                    Implementation of atoi() may be a useful read.
                    – chux
                    Nov 12 at 0:49

















                    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.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • 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%2f53249100%2fconvert-a-string-to-an-int-with-negative-numbers%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

                    Top Tejano songwriter Luis Silva dead of heart attack at 64

                    ReactJS Fetched API data displays live - need Data displayed static

                    政党