String to integer

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Freaker85

    #1

    String to integer

    Hello,

    I am new at programming in C and I am searching a manner to parse a
    string into an integer.
    I know how to do it in Java, but that doesn't work in C ;o)
    I searched the internet but I didn't found it yet.

    help please
    thank you
    Freaker85

  • ragi

    #2
    Re: String to integer


    Hi Friend,

    You can use library routine atoi(), for the same

    Thxs,
    ragi

    Freaker85 wrote:
    Hello,
    >
    I am new at programming in C and I am searching a manner to parse a
    string into an integer.
    I know how to do it in Java, but that doesn't work in C ;o)
    I searched the internet but I didn't found it yet.
    >
    help please
    thank you
    Freaker85

    Comment

    • shaanxxx

      #3
      Re: String to integer


      ragi wrote:
      Hi Friend,
      >
      You can use library routine atoi(), for the same
      >
      Thxs,
      ragi
      >
      Freaker85 wrote:
      >
      Hello,

      I am new at programming in C and I am searching a manner to parse a
      string into an integer.
      I know how to do it in Java, but that doesn't work in C ;o)
      I searched the internet but I didn't found it yet.

      help please
      thank you
      Freaker85
      you can use sscanf ()

      Comment

      • goose

        #4
        Re: String to integer

        Freaker85 wrote:
        Hello,
        >
        I am new at programming in C and I am searching a manner to parse a
        string into an integer.
        I know how to do it in Java, but that doesn't work in C ;o)
        I searched the internet but I didn't found it yet.
        >
        The following shows how to do it. Read the documentation
        on your system for sscanf.
        -------------------------------------
        #include <stdio.h>

        int main (void)
        {
        int dest = 0;
        char *s1[] = {
        "1234", /* 1234 */
        "0x61", /* 97 */
        "055", /* 45 */
        "-55", /* -55 */
        };
        int i;

        for (i=0; i<sizeof s1 / sizeof s1[0]; i++) {
        /* The return from sscanf tells you how many
        * values were successfully read in. Since
        * we are reading in only a single value
        * (dest), we check that we at get a return
        * of at least 1 from sscanf.
        */
        if (sscanf (s1[i], "%i", &dest)<1) {
        printf ("error %i\n", i);
        } else {
        /* We read in using %i, but print in
        * base 10 (%d). If we read in %d, then
        * we would not read 0x61 or 055 correctly.
        */
        printf ("%i\n", dest);
        }
        }
        return 0;
        }

        goose,

        Comment

        • goose

          #5
          Re: String to integer

          ragi wrote:
          <fixed toppost>
          Freaker85 wrote:
          >
          Hello,

          I am new at programming in C and I am searching a manner to parse a
          string into an integer.
          I know how to do it in Java, but that doesn't work in C ;o)
          I searched the internet but I didn't found it yet.

          help please
          thank you
          Freaker85
          Hi Friend,
          >
          You can use library routine atoi(), for the same
          >
          Welcome to clc. Please note that in the
          interests of maintaining a useful group,
          the posters here generaly:
          a) Avoid top-posting.
          b) Read the FAQ.

          goose,

          Comment

          • Christopher Benson-Manica

            #6
            Re: String to integer

            Freaker85 <t_De_smedt@hot mail.comwrote:
            I am new at programming in C and I am searching a manner to parse a
            string into an integer.
            The function atoi() will work, but you'll be better off using the more
            robust strtol(); atoi() provides no error checking, among other
            things.

            --
            C. Benson Manica | I *should* know what I'm talking about - if I
            cbmanica(at)gma il.com | don't, I need to know. Flames welcome.

            Comment

            • shaanxxx

              #7
              Re: String to integer


              goose wrote:
              >
              Welcome to clc. Please note that in the
              what is clc ?
              interests of maintaining a useful group,
              the posters here generaly:
              a) Avoid top-posting.
              who is doing top posting
              b) Read the FAQ.
              ?
              goose,

              Comment

              • Simon Biber

                #8
                Re: String to integer

                Freaker85 wrote:
                Hello,
                >
                I am new at programming in C and I am searching a manner to parse a
                string into an integer.
                I know how to do it in Java, but that doesn't work in C ;o)
                I searched the internet but I didn't found it yet.
                There are a few different functions that can parse strings into integers.

                atoi(s) is equivalent to (int)strtol(s, NULL, 10)
                atol(s) is equivalent to strtol(s, NULL, 10)

                With the exception that atoi and atol have undefined behaviour if the
                integer exceeds the int or long types respectively.

                strtol is preferred because it has well defined behaviour on overflow.
                There is also the flexibility of the second and third parameters. The
                second one can be NULL as in the examples above, or it can be a pointer
                to a char* variable that receives the location at which strtol stopped
                parsing. The third variable allows you to set the base for conversion (2
                for binary, 8 for octal, 10 for decimal, 16 for hexadecimal, etc.). A
                base of 0 makes it work like C integer literals: a leading zero
                indicates octal, and a leading 0x indicates hexadecimal.

                strtol("1111111 1", NULL, 2) == 255
                strtol("377", NULL, 8) == 255
                strtol("255", NULL, 10) == 255
                strtol("FF", NULL, 16) == 255

                strtol("255", NULL, 0) == 255
                strtol("0377", NULL, 0) == 255
                strtol("0xFF", NULL, 0) == 255

                Another option is sscanf, but like the atoi and atol functions, it has
                undefined behaviour if the integer is too big.

                --
                Simon.

                Comment

                • Simon Biber

                  #9
                  Re: String to integer

                  shaanxxx wrote:
                  goose wrote:
                  >
                  >Welcome to clc. Please note that in the
                  what is clc ?
                  clc is an abbreviation for comp.lang.c, the name of this newsgroup.
                  >interests of maintaining a useful group,
                  >the posters here generaly:
                  >a) Avoid top-posting.
                  who is doing top posting
                  ragi was top posting. It means putting your reply at the top of the
                  post. The correct way is to put your reply after each point that you are
                  replying to, like you and I do.
                  >b) Read the FAQ.
                  ?
                  The FAQ, or Frequently Asked Questions, is a document that answers
                  things that are frequently asked in comp.lang.c. If you do a Google
                  search for "c faq" you will find it.

                  --
                  Simon.

                  Comment

                  • Flash Gordon

                    #10
                    Re: String to integer

                    ragi wrote:
                    Hi Friend,
                    Your reply belongs under the text you are replying to, not above. After
                    snipping anything you are not replying to, of course. I've corrected it
                    this time.
                    Freaker85 wrote:
                    >
                    >Hello,
                    >>
                    >I am new at programming in C and I am searching a manner to parse a
                    >string into an integer.
                    >I know how to do it in Java, but that doesn't work in C ;o)
                    >I searched the internet but I didn't found it yet.
                    You can use library routine atoi(), for the same
                    Bad advice. It does not allow for error checking and if the string
                    represents a number that is out of range literally *anything* is allowed
                    to happen. Far better advice would be to use strtol assigning the result
                    to a long, checking the range before assigning to an int if that is what
                    you want, and also using the second parameter to detect errors in
                    conversion. Even if you don't check for conversion errors at least you
                    get defined behaviour if the number is too large.

                    Search the group for the many times this has been pointed out.
                    --
                    Flash Gordon.

                    Comment

                    • Default User

                      #11
                      Re: String to integer

                      ragi wrote:
                      >
                      Hi Friend,
                      Please don't top-post. Your replies belong following or interspersed
                      with properly trimmed quotes. See the majority of other posts in the
                      newsgroup, or:
                      <http://www.caliburn.nl/topposting.html >




                      Brian (hopes that's clearer)

                      Comment

                      • santosh

                        #12
                        Re: String to integer

                        Freaker85 wrote:
                        Hello,
                        >
                        I am new at programming in C and I am searching a manner to parse a
                        string into an integer.
                        I know how to do it in Java, but that doesn't work in C ;o)
                        I searched the internet but I didn't found it yet.
                        The easier, (relatively), way is to use sscanf(). It has the advantage
                        that you can scan multiple fields with a single call. The disadvantage
                        is that you don't get a useful return value upon failure, just whether
                        the field was converted and stored or not.

                        The more robust way is to use on of the many strtoXXXX functions
                        prototyped in <stdlib.h>. If you've to convert to integer values you
                        can use:
                        strtol() - long int
                        strtoul() - unsigned long int
                        strtoll() - long long int (C99 only)
                        strtoull() - unsigned long long int (C99 only)
                        strtoimax() - intmax_t (C99 only)
                        strtoumax() - uintmax_t (C99 only)

                        If the converted value should be a floating point type you can use:
                        strtof() - float (C99 only)
                        strtod() - double
                        strtold() - long double

                        These functions indicate the precise point within the string at which
                        conversion stopped, thus enabling you to decide whether the call was a
                        success or failure.

                        Of course, if you string is in a non-standard format, (eg. uses
                        regional notation, has additional characters like comma, currency
                        symbols etc.), then these functions will fail, when used as such. In
                        this case, you'll have to "tokenise" the string manually and pass a
                        "sanitised" version which can be converted by the strtoXXXX functions.

                        For details on using these functions consult a C Standard Library
                        reference manual. A good online source is:

                        <http://www.dinkumware. com/manuals/>

                        Comment

                        • CBFalconer

                          #13
                          Re: String to integer

                          santosh wrote:
                          Freaker85 wrote:
                          >>
                          >I am new at programming in C and I am searching a manner to parse
                          >a string into an integer.
                          >I know how to do it in Java, but that doesn't work in C ;o)
                          >I searched the internet but I didn't found it yet.
                          >
                          The easier, (relatively), way is to use sscanf(). It has the
                          advantage that you can scan multiple fields with a single call.
                          The disadvantage is that you don't get a useful return value
                          upon failure, just whether the field was converted and stored or
                          not.
                          >
                          The more robust way is to use on of the many strtoXXXX functions
                          prototyped in <stdlib.h>. If you've to convert to integer values
                          you can use:
                          scanf and friends generally can input data from a stream, without
                          requiring any advance assignment of buffers. The various strtoxx
                          routines require that the string first be loaded into a string,
                          which needs to be predeclared. This cannot handle such anomalies
                          as many trailing or leading zeroes, and in some cases they cannot
                          reliably detect all overflows. In particular, strtoul will accept
                          a negagive input, which is out of range (although the conversion is
                          specified).

                          I have built some routines to handle all this, at least for
                          integers, which I will get around to revising to handle the
                          complete set sooner or later. At present the code is as follows,
                          and there are some insecurities to do with input of negative
                          integers. An earlier version of the code is mounted on my site,
                          but this may help.

                          I expect I shall eventually change some names. Probably to the
                          stm2xx family, using similar naming conventions as does the strtoxx
                          family. This will avoid problems with names beginning with str.
                          Otherwise I would prefer the strm2xx family as a name.

                          /* ------------------------------------------------- *
                          * File txtinput.h *
                          * ------------------------------------------------- */

                          #ifndef H_txtinput_h
                          #define H_txtinput_h
                          # ifdef __cplusplus
                          extern "C" {
                          # endif

                          #include <stdio.h>

                          /* For licensing restrictions (GPL) see readme.txt in:
                          * <http://cbfalconer.home .att.net/download/txtio.zip>
                          *
                          * These stream input routines are written so that simple
                          * conditionals can be used:
                          *
                          * if (readxint(&myin t, stdin)) {
                          * do_error_recove ry; normally_abort_ to_somewhere;
                          * }
                          * else {
                          * do_normal_thing s; usually_much_lo nger_than_bad_c ase;
                          * }
                          *
                          * They allow overflow detection, and permit other routines to
                          * detect the character that terminated a numerical field. No
                          * string storage is required, thus there is no limitation on
                          * the length of input fields. For example, a number entered
                          * with a string of 1000 leading zeroes will not annoy these.
                          *
                          * The numerical input routines *NEVER* absorb a terminating
                          * char (including '\n'). Thus a sequence such as:
                          *
                          * err = readxint(&myint , stdin);
                          * flushln(stdin);
                          *
                          * will always consume complete lines, and after execution of
                          * readxint a further getc (or fgetc) will return the character
                          * that terminated the numeric field.
                          *
                          * They are also re-entrant, subject to the limitations of file
                          * systems. e.g interrupting readxint(v, stdin) operation with
                          * a call to readxwd(wd, stdin) would not be well defined, if
                          * the same stdin is being used for both calls. If ungetc is
                          * interruptible the run-time system is broken.

                          * Revised 2006-01-15 so that unsigned entry overflow (readxwd)
                          uses the normal C modulo (UINT_MAX + 1) operation. readxwd
                          still rejects an initial sign as an error.
                          */

                          /*--------------------------------------------------------------
                          * Skip all blanks on f. At completion getc(f) will return
                          * a non-blank character, which may be \n or EOF
                          *
                          * Skipblks returns the char that getc will next return, or EOF.
                          */
                          int skipblks(FILE *f);

                          /*--------------------------------------------------------------
                          * Skip all whitespace on f, including \n, \f, \v, \r. At
                          * completion getc(f) will return a non-blank character, which
                          * may be EOF
                          *
                          * Skipblks returns the char that getc will next return, or EOF.
                          */
                          int skipwhite(FILE *f);

                          /*--------------------------------------------------------------
                          * Read an unsigned value. Signal error for overflow or no
                          * valid number found. Returns 1 for error, 0 for noerror, EOF
                          * for EOF encountered before parsing a value.
                          *
                          * Skip all leading blanks on f. At completion getc(f) will
                          * return the character terminating the number, which may be \n
                          * or EOF among others. Barring EOF it will NOT be a digit. The
                          * combination of error, 0 result, and the next getc returning
                          * \n indicates that no numerical value was found on the line.
                          *
                          * If the user wants to skip all leading white space including
                          * \n, \f, \v, \r, he should first call "skipwhite( f);"
                          *
                          * Peculiarity: This specifically forbids a leading '+' or '-'.
                          */
                          int readxwd(unsigne d int *wd, FILE *f);

                          /*--------------------------------------------------------------
                          * Read a signed value. Signal error for overflow or no valid
                          * number found. Returns true for error, false for noerror. On
                          * overflow either INT_MAX or INT_MIN is returned in *val.
                          *
                          * Skip all leading blanks on f. At completion getc(f) will
                          * return the character terminating the number, which may be \n
                          * or EOF among others. Barring EOF it will NOT be a digit. The
                          * combination of error, 0 result, and the next getc returning
                          * \n indicates that no numerical value was found on the line.
                          *
                          * If the user wants to skip all leading white space including
                          * \n, \f, \v, \r, he should first call "skipwhite( f);"
                          *
                          * Peculiarity: an isolated leading '+' or '-' NOT immediately
                          * followed by a digit will return error and a value of 0, when
                          * the next getc will return that following non-digit. This is
                          * caused by the single level ungetc available.
                          */
                          int readxint(int *val, FILE *f);

                          /*--------------------------------------------------------------
                          * Flush input through an end-of-line marker inclusive.
                          */
                          void flushln(FILE *f);

                          # ifdef __cplusplus
                          }
                          # endif
                          #endif
                          /* End of txtinput.h */

                          /* ------------------------------------------------- *
                          * File txtinput.c *
                          * ------------------------------------------------- */

                          #include <limits.h /* xxxx_MAX, xxxx_MIN */
                          #include <ctype.h /* isdigit, isblank, isspace */
                          #include <stdio.h /* FILE, getc, ungetc */
                          #include "txtinput.h "

                          /* For licensing restrictions (GPL) see readme.txt in:
                          * <http://cbfalconer.home .att.net/download/txtio.zip>
                          *
                          * These stream input routines are written so that simple
                          * conditionals can be used:
                          *
                          * if (readxint(&myin t, stdin)) {
                          * do_error_recove ry; normally_abort_ to_somewhere;
                          * }
                          * else {
                          * do_normal_thing s; usually_much_lo nger_than_bad_c ase;
                          * }
                          *
                          * They allow overflow detection, and permit other routines to
                          * detect the character that terminated a numerical field. No
                          * string storage is required, thus there is no limitation on
                          * the length of input fields. For example, a number entered
                          * with a string of 1000 leading zeroes will not annoy these.
                          *
                          * The numerical input routines *NEVER* absorb a terminating
                          * char (including '\n'). Thus a sequence such as:
                          *
                          * err = readxint(&myint , stdin);
                          * flushln(stdin);
                          *
                          * will always consume complete lines, and after execution of
                          * readxint a further getc (or fgetc) will return the character
                          * that terminated the numeric field.
                          *
                          * They are also re-entrant, subject to the limitations of file
                          * systems. e.g interrupting readxint(v, stdin) operation with
                          * a call to readxwd(wd, stdin) would not be well defined, if
                          * the same stdin is being used for both calls. If ungetc is
                          * interruptible the run-time system is broken.
                          *
                          * Originally issued 2002-10-07
                          *
                          * Revised 2006-01-15 so that unsigned entry overflow (readxwd)
                          uses the normal C modulo (UINT_MAX + 1) operation. readxwd
                          still rejects an initial sign as an error.
                          */

                          /* -------------------------------------------------------------
                          * Skip to non-blank on f, and return that char. or EOF The next
                          * char that getc(f) will return is unknown. Local use only.
                          */
                          static int ignoreblks(FILE *f)
                          {
                          int ch;

                          do {
                          ch = getc(f);
                          } while ((' ' == ch) || ('\t' == ch));
                          /* while (isblank(ch)); */ /* for C99 */
                          return ch;
                          } /* ignoreblks */

                          /*--------------------------------------------------------------
                          * Skip all blanks on f. At completion getc(f) will return
                          * a non-blank character, which may be \n or EOF
                          *
                          * Skipblks returns the char that getc will next return, or EOF.
                          */
                          int skipblks(FILE *f)
                          {
                          return ungetc(ignorebl ks(f), f);
                          } /* skipblks */

                          /*--------------------------------------------------------------
                          * Skip all whitespace on f, including \n, \f, \v, \r. At
                          * completion getc(f) will return a non-blank character, which
                          * may be EOF
                          *
                          * Skipwhite returns the char that getc will next return, or EOF.
                          */
                          int skipwhite(FILE *f)
                          {
                          int ch;

                          do {
                          ch = getc(f);
                          } while (isspace(ch));
                          return ungetc(ch, f);
                          } /* skipwhite */

                          /*--------------------------------------------------------------
                          * Read an unsigned value. Signal error for overflow or no
                          * valid number found. Returns 1 for error, 0 for noerror, EOF
                          * for EOF encountered before parsing a value.
                          *
                          * Skip all leading blanks on f. At completion getc(f) will
                          * return the character terminating the number, which may be \n
                          * or EOF among others. Barring EOF it will NOT be a digit. The
                          * combination of error, 0 result, and the next getc returning
                          * \n indicates that no numerical value was found on the line.
                          *
                          * If the user wants to skip all leading white space including
                          * \n, \f, \v, \r, he should first call "skipwhite( f);"
                          *
                          * Peculiarity: This specifically forbids a leading '+' or '-'.
                          */
                          int readxwd(unsigne d int *wd, FILE *f)
                          {
                          unsigned int value, digit;
                          int status;
                          int ch;

                          #define UWARNLVL (UINT_MAX / 10U)
                          #define UWARNDIG (UINT_MAX - UWARNLVL * 10U)

                          value = 0; /* default */
                          status = 1; /* default error */

                          ch = ignoreblks(f);

                          if (EOF == ch) status = EOF;
                          else if (isdigit(ch)) status = 0; /* digit, no error */

                          while (isdigit(ch)) {
                          digit = ch - '0';
                          if ((value UWARNLVL) ||
                          ((UWARNLVL == value) && (digit UWARNDIG))) {
                          status = 1; /* overflow */
                          value -= UWARNLVL;
                          }
                          value = 10 * value + digit;
                          ch = getc(f);
                          } /* while (ch is a digit) */

                          *wd = value;
                          ungetc(ch, f);
                          return status;
                          } /* readxwd */

                          /*--------------------------------------------------------------
                          * Read a signed value. Signal error for overflow or no valid
                          * number found. Returns true for error, false for noerror. On
                          * overflow either INT_MAX or INT_MIN is returned in *val.
                          *
                          * Skip all leading blanks on f. At completion getc(f) will
                          * return the character terminating the number, which may be \n
                          * or EOF among others. Barring EOF it will NOT be a digit. The
                          * combination of error, 0 result, and the next getc returning
                          * \n indicates that no numerical value was found on the line.
                          *
                          * If the user wants to skip all leading white space including
                          * \n, \f, \v, \r, he should first call "skipwhite( f);"
                          *
                          * Peculiarity: an isolated leading '+' or '-' NOT immediately
                          * followed by a digit will return error and a value of 0, when
                          * the next getc will return that following non-digit. This is
                          * caused by the single level ungetc available.
                          */
                          int readxint(int *val, FILE *f)
                          {
                          unsigned int value;
                          int status, negative;
                          int ch;

                          *val = value = 0; /* default */
                          status = 1; /* default error */
                          negative = 0;

                          ch = ignoreblks(f);

                          if (EOF != ch) {
                          if (('+' == ch) || ('-' == ch)) {
                          negative = ('-' == ch);
                          ch = ignoreblks(f); /* absorb any sign */
                          }

                          if (isdigit(ch)) { /* digit, no error */
                          ungetc(ch, f);
                          status = readxwd(&value, f);
                          ch = getc(f); /* This terminated readxwd */
                          }

                          if (0 == status) { /* no readxwd overflow */
                          if (!negative && (value <= INT_MAX))
                          *val = value;
                          else if (negative && (value < UINT_MAX) &&
                          ((value - 1) <= -(1 + INT_MIN)))
                          *val = -value;
                          else { /* overflow */
                          status = 1; /* do whatever the native system does */
                          if (negative) *val = -value;
                          else *val = value;
                          }
                          }
                          else if (negative) *val = -value;
                          else *val = value;
                          }
                          ungetc(ch, f);
                          return status;
                          } /* readxint */

                          /*-----------------------------------------------------
                          * Flush input through an end-of-line marker inclusive.
                          */
                          void flushln(FILE *f)
                          {
                          int ch;

                          do {
                          ch = getc(f);
                          } while (('\n' != ch) && (EOF != ch));
                          } /* flushln */

                          /* End of txtinput.c */

                          --
                          Some informative links:
                          news:news.annou nce.newusers
                          Latest news coverage, email, free stock quotes, live scores and video are just the beginning. Discover more every day at Yahoo!






                          Comment

                          • shaanxxx

                            #14
                            Re: String to integer

                            Freaker85 wrote:
                            Hello,
                            >
                            I am new at programming in C and I am searching a manner to parse a
                            string into an integer.
                            I know how to do it in Java, but that doesn't work in C ;o)
                            I searched the internet but I didn't found it yet.
                            >
                            help please
                            thank you
                            Freaker85
                            refer postgres code :



                            Try to concentrate on use of "sscanf" in formatting.c. Code is self
                            explainatory.
                            You will get a feel of open world.

                            Comment

                            Working...