Strtod

Обзор

Функция разбирает строку Си , представляя её содержимое в виде числа с плавающей точкой и возвращает её значение . Если  — не нуль-указатель, то функция устанавливает значение, на которое указывает , равным первому символу после числа.

Вначале функция отбрасывает все пробелы, пока не встретится первый непробельный символ. Затем, начиная с этого символа, считывает все символы, соответствующие синтаксису как у литералов с плавающей точкой, и интерпретирует их в виде числовых значений. Указатель на оставшуюся часть строки после последнего корректного символа сохраняется в объекте, на который указывает .

Корректной последовательностью чисел с плавающей точкой для считается последовательность, удовлетворяющая следующим условиям:

  • Знак положительного или отрицательного числа (необязательно)
  • Последовательность цифр, как вариант, может содержать десятичную точку
  • Дополнительная экспонентная часть, которая сама по себе состоит из символа ‘e’ или ‘E’, после которого следует дополнительный знак и последовательность цифр.

Если первая последовательность непробельных символов в не содержит корректного числа с плавающей точкой как описано выше, или такой корректной последовательности не существует, так как, например, или пуст или содержит только символы пробела, то преобразование не выполняется.

COLOPHON top

       This page is part of release 5.08 of the Linux man-pages project.  A
       description of the project, information about reporting bugs, and the
       latest version of this page, can be found at
       https://www.kernel.org/doc/man-pages/.

GNU                              2020-06-09                       STRTOUL(3)

Pages that refer to this page:
capsh(1), 
a64l(3), 
atof(3), 
atoi(3), 
atol(3), 
atoll(3), 
atoq(3), 
fscanf(3), 
l64a(3), 
scanf(3), 
sscanf(3), 
strtod(3), 
strtof(3), 
strtoimax(3), 
strtol(3), 
strtold(3), 
strtoll(3), 
strtoq(3), 
strtoumax(3), 
vfscanf(3), 
vscanf(3), 
vsscanf(3), 
logrotate.conf(5), 
bpf-helpers(7), 
BPF-HELPERS(7), 
logrotate(8)

Notes

Since strtoul() can legitimately return 0 or ULONG_MAX (ULLONG_MAX for strtoull()) on both success and failure, the calling
program should set errno to 0 before the call, and then determine if an error occurred by checking whether errno has a nonzero value after the
call.

In locales other than the «C» locale, other strings may be accepted. (For example, the thousands separator of the current locale may be supported.)

BSD also has

u_quad_t strtouq(const char *nptr, char **endptr, int base);

with completely analogous definition. Depending on the wordsize of the current architecture, this may be equivalent to strtoull() or to
strtoul().

Negative values are considered valid input and are silently converted to the equivalent unsigned long int value.

Example 2: strtoull() function with different bases

When you run the program, the output will be:

148ax to Unsigned Long Long Int with base-5 = 9
End String = 8ax
 
148ax to Unsigned Long Long Int with base-15 = 4405
End String = x
 
148ax to Unsigned Long Long Int with base-35 = 1682308
End String =

The strtoull() function ignores all the leading whitespace characters until the primary non-whitespace character is found.

In general, a valid integer argument for strtoull() function has the following form:

Then, beginning from this character, it takes as many characters as possible that forms a valid integer representation and converts them to a long long int value. Whatever is left of the string after the last valid character is ignored and has no effect on the result.

Example 2: strtol() function with different bases

When you run the program, the output will be:

128bz to Long Int with base-5 = 7
End String = 8bxz

128bz to Long Int with base-12 = 2123
End String = xz

128bz to Long Int with base-36 = 64214135
End String =

The strtol() function ignores all the leading whitespace characters until the primary non-whitespace character is found.

In general, a valid integer argument for strtol() function has the following form:

Then, beginning from this character, it takes as many characters as possible that forms a valid integer representation and converts them to a long int value. Whatever is left of the string after the last valid character is ignored and has no effect on the result.

DESCRIPTION top

       The strtod(), strtof(), and strtold() functions convert the initial
       portion of the string pointed to by nptr to double, float, and long
       double representation, respectively.

       The expected form of the (initial portion of the) string is optional
       leading white space as recognized by isspace(3), an optional plus
       ('+') or minus sign ('-') and then either (i) a decimal number, or
       (ii) a hexadecimal number, or (iii) an infinity, or (iv) a NAN (not-
       a-number).

       A decimal number consists of a nonempty sequence of decimal digits
       possibly containing a radix character (decimal point, locale-
       dependent, usually '.'), optionally followed by a decimal exponent.
       A decimal exponent consists of an 'E' or 'e', followed by an optional
       plus or minus sign, followed by a nonempty sequence of decimal
       digits, and indicates multiplication by a power of 10.

       A hexadecimal number consists of a "0x" or "0X" followed by a
       nonempty sequence of hexadecimal digits possibly containing a radix
       character, optionally followed by a binary exponent.  A binary
       exponent consists of a 'P' or 'p', followed by an optional plus or
       minus sign, followed by a nonempty sequence of decimal digits, and
       indicates multiplication by a power of 2.  At least one of radix
       character and binary exponent must be present.

       An infinity is either "INF" or "INFINITY", disregarding case.

       A NAN is "NAN" (disregarding case) optionally followed by a string,
       (n-char-sequence), where n-char-sequence specifies in an
       implementation-dependent way the type of NAN (see NOTES).

DESCRIPTION top

       The strtol() function converts the initial part of the string in nptr
       to a long integer value according to the given base, which must be
       between 2 and 36 inclusive, or be the special value 0.

       The string may begin with an arbitrary amount of white space (as
       determined by isspace(3)) followed by a single optional '+' or '-'
       sign.  If base is zero or 16, the string may then include a "0x" or
       "0X" prefix, and the number will be read in base 16; otherwise, a
       zero base is taken as 10 (decimal) unless the next character is '0',
       in which case it is taken as 8 (octal).

       The remainder of the string is converted to a long int value in the
       obvious manner, stopping at the first character which is not a valid
       digit in the given base.  (In bases above 10, the letter 'A' in
       either uppercase or lowercase represents 10, 'B' represents 11, and
       so forth, with 'Z' representing 35.)

       If endptr is not NULL, strtol() stores the address of the first
       invalid character in *endptr.  If there were no digits at all,
       strtol() stores the original value of nptr in *endptr (and returns
       0).  In particular, if *nptr is not '\0' but **endptr is '\0' on
       return, the entire string is valid.

       The strtoll() function works just like the strtol() function but
       returns a long long integer value.

EXAMPLES top

       The program shown below demonstrates the use of strtol().  The first
       command-line argument specifies a string from which strtol() should
       parse a number.  The second (optional) argument specifies the base to
       be used for the conversion.  (This argument is converted to numeric
       form using atoi(3), a function that performs no error checking and
       has a simpler interface than strtol().)  Some examples of the results
       produced by this program are the following:

           $ ./a.out 123
           strtol() returned 123
           $ ./a.out '    123'
           strtol() returned 123
           $ ./a.out 123abc
           strtol() returned 123
           Further characters after number: abc
           $ ./a.out 123abc 55
           strtol: Invalid argument
           $ ./a.out ''
           No digits were found
           $ ./a.out 4000000000
           strtol: Numerical result out of range

   Program source

       #include <stdlib.h>
       #include <limits.h>
       #include <stdio.h>
       #include <errno.h>

       int
       main(int argc, char *argv[])
       {
           int base;
           char *endptr, *str;
           long val;

           if (argc < 2) {
               fprintf(stderr, "Usage: %s str \n", argv);
               exit(EXIT_FAILURE);
           }

           str = argv;
           base = (argc > 2) ? atoi(argv) : 10;

           errno = 0;    /* To distinguish success/failure after call */
           val = strtol(str, &endptr, base);

           /* Check for various possible errors */

           if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
                   || (errno != 0 && val == 0)) {
               perror("strtol");
               exit(EXIT_FAILURE);
           }

           if (endptr == str) {
               fprintf(stderr, "No digits were found\n");
               exit(EXIT_FAILURE);
           }

           /* If we got here, strtol() successfully parsed a number */

           printf("strtol() returned %ld\n", val);

           if (*endptr != '\0')        /* Not necessarily an error... */
               printf("Further characters after number: %s\n", endptr);

           exit(EXIT_SUCCESS);
       }

DESCRIPTION top

       The strtod(), strtof(), and strtold() functions convert the initial
       portion of the string pointed to by nptr to double, float, and long
       double representation, respectively.

       The expected form of the (initial portion of the) string is optional
       leading white space as recognized by isspace(3), an optional plus
       ('+') or minus sign ('-') and then either (i) a decimal number, or
       (ii) a hexadecimal number, or (iii) an infinity, or (iv) a NAN (not-
       a-number).

       A decimal number consists of a nonempty sequence of decimal digits
       possibly containing a radix character (decimal point, locale-
       dependent, usually '.'), optionally followed by a decimal exponent.
       A decimal exponent consists of an 'E' or 'e', followed by an optional
       plus or minus sign, followed by a nonempty sequence of decimal
       digits, and indicates multiplication by a power of 10.

       A hexadecimal number consists of a "0x" or "0X" followed by a
       nonempty sequence of hexadecimal digits possibly containing a radix
       character, optionally followed by a binary exponent.  A binary
       exponent consists of a 'P' or 'p', followed by an optional plus or
       minus sign, followed by a nonempty sequence of decimal digits, and
       indicates multiplication by a power of 2.  At least one of radix
       character and binary exponent must be present.

       An infinity is either "INF" or "INFINITY", disregarding case.

       A NAN is "NAN" (disregarding case) optionally followed by a string,
       (n-char-sequence), where n-char-sequence specifies in an
       implementation-dependent way the type of NAN (see NOTES).

SYNOPSIS

#include <stdlib.h>

unsigned long strtoul(const char *nptr,
char **endptr, int base);

unsigned long long strtoul(const char *nptr,
char **endptr, int base);

uintmax_t strtoumax(const char *nptr,
char **endptr, int base);

uquad_t strtouq(const char *nptr,
char **endptr, int base);

unsigned long strtoul_l(const char *nptr,
char **endptr, int base, locale_t locale);

unsigned long long strtoull_l(const char *nptr,
char **endptr, int base, locale_t locale);

#include <inttypes.h>

uintmax_t strtoumax(const char *nptr,
char **endptr, int base);

uintmax_t strtoumax_l(const char *nptr,
char **endptr, int base, locale_t locale);

Другие решения

Обратите внимание, что имена, начинающиеся с подчеркивания, зарезервированы для реализации; Лучше избегать использования таких имен в вашем коде. Следовательно, должно быть просто ,. Полная спецификация обработки ошибок для и его родственники сложны, удивительно сложны, когда вы впервые сталкиваетесь с ним

Одна вещь, которую вы делаете абсолютно правильно, это использование функции для вызова ; использование этого «сырого» в коде, вероятно, не правильно

Полная спецификация обработки ошибок для и его родственники сложны, удивительно сложны, когда вы впервые сталкиваетесь с ним. Одна вещь, которую вы делаете абсолютно правильно, это использование функции для вызова ; использование этого «сырого» в коде, вероятно, не правильно.

Поскольку вопрос помечен как C, так и C ++, я процитирую стандарт C2011; Вы можете найти соответствующую формулировку в стандарте C ++ для себя.

Помните, что никакая стандартная функция библиотеки C никогда не устанавливается до 0. Поэтому, чтобы быть надежным, вы должны установить до нуля перед звонком ,

Так что ваши функция может выглядеть так:

Обратите внимание, что в случае ошибки возвращается 0 или LONG_MIN или LONG_MAX, в зависимости от того, что вернулся. Если ваш вызывающий код должен знать, было ли преобразование успешным или нет, вам нужен другой интерфейс функции — см

Ниже. Также обратите внимание, что ошибки должны быть напечатаны на скорее, чем и сообщения об ошибках должны заканчиваться символом новой строки ; если они не, они не гарантированы, чтобы появиться своевременно.

Теперь в библиотечном коде вы, вероятно, не хотите печатать, и ваш вызывающий код может захотеть узнать, было ли преобразование успешным или нет, так что вы можете также пересмотреть интерфейс. В этом случае вы, вероятно, измените функцию, чтобы она возвращала указание успеха / неудачи:

который вы могли бы использовать как:

Если вам необходимо различать «конечный мусор», «недопустимая числовая строка», «значение слишком большое» и «значение слишком маленькое» (и «нет ошибок»), вы должны использовать целое число или вместо логического кода возврата. Если вы хотите разрешить конечные пробелы, но не использовать другие символы, или если вы не хотите разрешать начальные пробелы, у вас есть больше работы в функции. Код допускает восьмеричное, десятичное и шестнадцатеричное; если вы хотите строго десятичную, вам нужно изменить 0 до 10 в вызове ,

Если ваши функции должны маскироваться как часть стандартной библиотеки, они не должны устанавливать в навсегда, так что вам нужно обернуть код, чтобы сохранить :

42

Вы должны проверять

Вы также должны иметь возможность проверить значение errno после вызова strotol в соответствии с этим:

1

Example 4: strtod Cases for INFINITY and NaN

When you run the program, the output will be:

INFINITY to Double = inf
End String =

Infabc to Double = inf
End String = abc

NaN12a to Double = nan
End String = 12a

In general, a valid floating point argument for strtod() function has the following form:

digits]

The strtod() function ignores all the leading whitespace characters until the primary non-whitespace character is found.

Then, beginning from this character, it takes as many characters as possible that forms a valid floating-point representation and converts them to a floating point value. Whatever is left of the string after the last valid character is stored in the object pointed by end.

Syntax

The syntax for the strtol function in the C Language is:

long int strtol(const char *nptr, char **endptr, int base);

Parameters or Arguments

nptr
A pointer to a string to convert to a long integer.
endptr
It is used by the strtol function to indicate where the conversion stopped. The strtol function will modify endptr (if endptr is not a null pointer) so that endptr points to the first character that was not converted.
base
The base of the number being converted. If base is between 2 and 36, it is used as the radix of the number. If base is zero, the number is assumed to be decimal unless the converted number starts with O (for Octal), Ox (for hex) or OX (for hex).

Example 1: How strtol() works in C++?

When you run the program, the output will be:

Number in  String = 27ab_1x
Number in Long Int = 27
End String = ab_1x

Number in  String = 27
Number in Long Int = 27
Null pointer

A valid integer value for strtol() function consists of:

  • An optional + or — sign.
  • A prefix 0 for octal base (applies only when base = 8 or 0).
  • A prefix 0x or 0X for hexadecimal base (applies only when base = 16 or 0).
  • A sequence of digits and/or alphabets (if base is greater than 10).

The valid values for parameter base is {0, 2, 3, …, 35, 36}. A set of valid digits for base 2 is {0, 1}, for base 3 is {0, 1, 2} and so on. For bases starting from 11 to 36, valid digits include alphabets. The set of valid digits for base 11 is {0, 1, …, 9, A, a}, for base 12 is {0, 1, …, 9, A, a, B, b} and so on.

Note: It is important to remember that a valid character for one base can end up in the invalid string for another base as in the example below.

NOTES top

       Since strtol() can legitimately return 0, LONG_MAX, or LONG_MIN
       (LLONG_MAX or LLONG_MIN for strtoll()) on both success and failure,
       the calling program should set errno to 0 before the call, and then
       determine if an error occurred by checking whether errno has a
       nonzero value after the call.

       According to POSIX.1, in locales other than the "C" and "POSIX",
       these functions may accept other, implementation-defined numeric
       strings.

       BSD also has

           quad_t strtoq(const char *nptr, char **endptr, int base);

       with completely analogous definition.  Depending on the wordsize of
       the current architecture, this may be equivalent to strtoll() or to
       strtol().

DESCRIPTION top

       The strtoul() function converts the initial part of the string in
       nptr to an unsigned long int value according to the given base, which
       must be between 2 and 36 inclusive, or be the special value 0.

       The string may begin with an arbitrary amount of white space (as
       determined by isspace(3)) followed by a single optional '+' or '-'
       sign.  If base is zero or 16, the string may then include a "0x"
       prefix, and the number will be read in base 16; otherwise, a zero
       base is taken as 10 (decimal) unless the next character is '0', in
       which case it is taken as 8 (octal).

       The remainder of the string is converted to an unsigned long int
       value in the obvious manner, stopping at the first character which is
       not a valid digit in the given base.  (In bases above 10, the letter
       'A' in either uppercase or lowercase represents 10, 'B' represents
       11, and so forth, with 'Z' representing 35.)

       If endptr is not NULL, strtoul() stores the address of the first
       invalid character in *endptr.  If there were no digits at all,
       strtoul() stores the original value of nptr in *endptr (and returns
       0).  In particular, if *nptr is not '\0' but **endptr is '\0' on
       return, the entire string is valid.

       The strtoull() function works just like the strtoul() function but
       returns an unsigned long long int value.

strtol Example

Let’s look at an example to see how you would use the strtol function in a C program:

/* Example using strtol by TechOnTheNet.com */

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

int main(int argc, const char * argv[])
{
    /* Define temporary variables */
    char value;
    char *eptr;
    long result;

    /* Copy a value into the variable */
    /* It's okay to have whitespace before the number */
    strcpy(value, " 123");

    /* Convert the provided value to a decimal long */
    result = strtol(value, &eptr, 10);

    /* If the result is 0, test for an error */
    if (result == 0)
    {
        /* If a conversion error occurred, display a message and exit */
        if (errno == EINVAL)
        {
            printf("Conversion error occurred: %d\n", errno);
            exit(0);
        }

        /* If the value provided was out of range, display a warning message */
        if (errno == ERANGE)
            printf("The value provided was out of range\n");
    }

    /* Display the converted result */
    printf("%ld decimal\n", result);

    /* Copy a hexadecimal value into the variable */
    strcpy(value, "0x19e");

    /* Convert the provided value to a decimal long */
    result = strtol(value, &eptr, 16);

    /* If the result is 0, test for an error */
    if (result == 0)
    {
        /* If a conversion error occurred, display a message and exit */
        if (errno == EINVAL)
        {
            printf("Conversion error occurred: %d\n", errno);
            exit(0);
        }

        /* If the value provided was out of range, display a warning message */
        if (errno == ERANGE)
            printf("The value provided was out of range\n");
    }

    /* Display the converted result */
    printf("%lx hexadecimal\n", result);

    return 0;
}

When compiled and run, this application will output:

123 decimal
19e hexadecimal

Example 2: strtod() function without trailing characters

When you run the program, the output will be:

Number in End String = 12.44b 0xy
Number in Double = 12.44
Null pointer

A valid floating-point value for strtod() function consists of an optional + or — sign followed by one of the following sets:

  • For decimal floating-point value:

    • A group of decimal digits (0-9), optionally containing a decimal point (.).
      For example: 13.170, -5.63, etc .

    • An optional exponent part (e or E) followed by an optional + or — sign and non-empty sequence of decimal digits.
      For example: 3.46101e+007, 13.19e-013, etc.

  • For hexadecimal floating-point value:

    • A string starting with 0x or 0X, followed by a non-empty sequence of hexadecimal digits, optionally containing a decimal point (.).
      For Example: 0xfa5, -0xb1f.24, etc.

    • An optional exponent part (p or P) followed by an optional + or — sign and non-empty sequence of hexadecimal digits.
      For Example: 0x51c.23p5, -0x2a.3p-3, etc.

  • Infinity:

    INF or INFINITY (ignoring case).
    For Example: -Inf, InfiNiTy, etc.

  • NaN (Not a Number):

    NAN or NANsequence (ignoring case) where sequence is a sequence of characters consisting only of alphanumeric characters or the underscore (_). The result is a quiet NaN.
    For Example: Nan, NaNab1, etc.

Library Functions

Following are the functions defined in the header string.h −

Sr.No. Function & Description
1 void *memchr(const void *str, int c, size_t n)

Searches for the first occurrence of the character c (an unsigned char) in the first n bytes of the string pointed to, by the argument str.

2 int memcmp(const void *str1, const void *str2, size_t n)

Compares the first n bytes of str1 and str2.

3 void *memcpy(void *dest, const void *src, size_t n)

Copies n characters from src to dest.

4 void *memmove(void *dest, const void *src, size_t n)

Another function to copy n characters from str2 to str1.

5 void *memset(void *str, int c, size_t n)

Copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str.

6 char *strcat(char *dest, const char *src)

Appends the string pointed to, by src to the end of the string pointed to by dest.

7 char *strncat(char *dest, const char *src, size_t n)

Appends the string pointed to, by src to the end of the string pointed to, by dest up to n characters long.

8 char *strchr(const char *str, int c)

Searches for the first occurrence of the character c (an unsigned char) in the string pointed to, by the argument str.

9 int strcmp(const char *str1, const char *str2)

Compares the string pointed to, by str1 to the string pointed to by str2.

10 int strncmp(const char *str1, const char *str2, size_t n)

Compares at most the first n bytes of str1 and str2.

11 int strcoll(const char *str1, const char *str2)

Compares string str1 to str2. The result is dependent on the LC_COLLATE setting of the location.

12 char *strcpy(char *dest, const char *src)

Copies the string pointed to, by src to dest.

13 char *strncpy(char *dest, const char *src, size_t n)

Copies up to n characters from the string pointed to, by src to dest.

14 size_t strcspn(const char *str1, const char *str2)

Calculates the length of the initial segment of str1 which consists entirely of characters not in str2.

15 char *strerror(int errnum)

Searches an internal array for the error number errnum and returns a pointer to an error message string.

16 size_t strlen(const char *str)

Computes the length of the string str up to but not including the terminating null character.

17 char *strpbrk(const char *str1, const char *str2)

Finds the first character in the string str1 that matches any character specified in str2.

18 char *strrchr(const char *str, int c)

Searches for the last occurrence of the character c (an unsigned char) in the string pointed to by the argument str.

19 size_t strspn(const char *str1, const char *str2)

Calculates the length of the initial segment of str1 which consists entirely of characters in str2.

20 char *strstr(const char *haystack, const char *needle)

Finds the first occurrence of the entire string needle (not including the terminating null character) which appears in the string haystack.

21 char *strtok(char *str, const char *delim)

Breaks string str into a series of tokens separated by delim.

22 size_t strxfrm(char *dest, const char *src, size_t n)

Transforms the first n characters of the string src into current locale and places them in the string dest.

Previous Page
Print Page

Next Page  

Example 2: strtoll() function with different bases

When you run the program, the output will be:

23ajz to Long Long Int with base-7 = 17
End String = ajz

23ajz to Long Long Int with base-20 = 17419
End String = z

23ajz to Long Long Int with base-36 = 3512879
End String =

The strtoll() function ignores all the leading whitespace characters until the primary non-whitespace character is found.

In general, a valid integer argument for strtoll() function has the following form:

Then, beginning from this character, it takes as many characters as possible that forms a valid integer representation and converts them to a long long int value. Whatever is left of the string after the last valid character is ignored and has no effect on the result.

Description

The strtoul() function converts the initial part of the string in nptr to an unsigned long int value according to the given
base, which must be between 2 and 36 inclusive, or be the special value 0.

The string may begin with an arbitrary amount of white space (as determined by isspace(3)) followed by a single optional ‘+’ or ‘-‘ sign. If
base is zero or 16, the string may then include a «0x» prefix, and the number will be read in base 16; otherwise, a zero base is taken as 10
(decimal) unless the next character is ‘0’, in which case it is taken as 8 (octal).

The remainder of the string is converted to an unsigned long int value in the obvious manner, stopping at the first character which is not a valid
digit in the given base. (In bases above 10, the letter ‘A’ in either upper or lower case represents 10, ‘B’ represents 11, and so forth, with ‘Z’ representing
35.)

If endptr is not NULL, strtoul() stores the address of the first invalid character in *endptr. If there were no digits at all,
strtoul() stores the original value of nptr in *endptr (and returns 0). In particular, if *nptr is not ‘\0’ but **endptr is
‘\0’ on return, the entire string is valid.

The strtoull() function works just like the strtoul() function but returns an unsigned long long int value.

Description

The strtod(), strtof(), and strtold() functions convert the initial portion of the string pointed to by nptr to double,
float, and long double representation, respectively.

The expected form of the (initial portion of the) string is optional leading white space as recognized by isspace(3), an optional plus (‘+’) or minus
sign (‘-‘) and then either (i) a decimal number, or (ii) a hexadecimal number, or (iii) an infinity, or (iv) a NAN (not-a-number).

A decimal number consists of a nonempty sequence of decimal digits possibly containing a radix character (decimal point, locale-dependent, usually
‘.’), optionally followed by a decimal exponent. A decimal exponent consists of an ‘E’ or ‘e’, followed by an optional plus or minus sign, followed by a
nonempty sequence of decimal digits, and indicates multiplication by a power of 10.

A hexadecimal number consists of a «0x» or «0X» followed by a nonempty sequence of hexadecimal digits possibly containing a radix character,
optionally followed by a binary exponent. A binary exponent consists of a ‘P’ or ‘p’, followed by an optional plus or minus sign, followed by a nonempty
sequence of decimal digits, and indicates multiplication by a power of 2. At least one of radix character and binary exponent must be present.

An infinity is either «INF» or «INFINITY», disregarding case.

A NAN is «NAN» (disregarding case) optionally followed by ‘(‘, a sequence of characters, followed by ‘)’. The character string specifies in an
implementation-dependent way the type of NAN.

NOTES top

       Since strtoul() can legitimately return 0 or ULONG_MAX (ULLONG_MAX
       for strtoull()) on both success and failure, the calling program
       should set errno to 0 before the call, and then determine if an error
       occurred by checking whether errno has a nonzero value after the
       call.

       In locales other than the "C" locale, other strings may be accepted.
       (For example, the thousands separator of the current locale may be
       supported.)

       BSD also has

           u_quad_t strtouq(const char *nptr, char **endptr, int base);

       with completely analogous definition.  Depending on the wordsize of
       the current architecture, this may be equivalent to strtoull() or to
       strtoul().

       Negative values are considered valid input and are silently converted
       to the equivalent unsigned long int value.

DESCRIPTION

The strtoul() class of functions
convert the string pointed to by nptr into unsigned long, unsigned long long, uquad_t or uintmax_t.
by nptr to an unsigned long int representation.
This function recognizes (in order) an optional string of spaces,
an optional base indicator ( for octal, X or
x for hexadecimal), and a string of digits. The first unrecognized
character ends the string. A pointer to this unrecognized character is stored
in the object addressed by endptr, if endptr
is not NULL.

If base is non-zero, its
value determines the set of recognized digits and also overrides
the optional base indicator character. If base is zero,
nptr is assumed to be base 10, unless an optional base
indicator character is given.

COLOPHON top

       This page is part of release 5.08 of the Linux man-pages project.  A
       description of the project, information about reporting bugs, and the
       latest version of this page, can be found at
       https://www.kernel.org/doc/man-pages/.

Linux                            2020-06-09                        STRTOD(3)

Pages that refer to this page:
gawk(1), 
pcpintro(1), 
PCPIntro(1), 
pmstore(1), 
strace(1), 
atof(3), 
atoi(3), 
atol(3), 
atoll(3), 
atoq(3), 
fscanf(3), 
nan(3), 
nanf(3), 
nanl(3), 
scanf(3), 
sscanf(3), 
strfromd(3), 
strfromf(3), 
strfroml(3), 
strtol(3), 
strtoll(3), 
strtoq(3), 
strtoul(3), 
strtoull(3), 
strtouq(3), 
vfscanf(3), 
vscanf(3), 
vsscanf(3), 
locale(7)

strtod Example

Let’s look at an example to see how you would use the strtod function in a C program:

/* Example using strtod by TechOnTheNet.com */

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

int main(int argc, const char * argv[])
{
    /* Define temporary variables */
    char value;
    char *eptr;
    double result;

    /* Copy a value into the variable */
    /* It's okay to have whitespace before the number */
    strcpy(value, " 958");

    /* Convert the provided value to a double */
    result = strtod(value, &eptr);

    /* If the result is 0, test for an error */
    if (result == 0)
    {
        /* If the value provided was out of range, display a warning message */
        if (errno == ERANGE)
            printf("The value provided was out of range\n");
    }

    /* Display the converted result */
    printf("%f decimal\n", result);

    /* Copy a hexadecimal value into the variable */
    strcpy(value, "0x8b2");

    /* Convert the hexadecimal provided value to a double */
    result = strtod(value, &eptr);

    /* If the result is 0, test for an error */
    if (result == 0)
    {
        /* If the value provided was out of range, display a warning message */
        if (errno == ERANGE)
            printf("The value provided was out of range\n");
    }

    /* Display the converted result */
    printf("%f decimal\n", result);

    return 0;
}

When compiled and run, this application will output:

958.000000 decimal
2226.000000 decimal

Example 1: How strtoll() function works?

When you run the program, the output will be:

String value = 13.5ab_1x
Long long int value = 13
End String = .5ab_1x
String value = 13
Long long int value = 13
Null pointer

A valid integer value for strtoll() function consists of:

  • An optional + or — sign.
  • A prefix 0 for octal base (applies only when base = 8 or 0).
  • A prefix 0x or 0X for hexadecimal base (applies only when base = 16 or 0).
  • A sequence of digits and/or alphabets (if base is greater than 10).

The valid values for parameter base is {0, 2, 3, …, 35, 36}. A set of valid digits for base 2 is {0, 1}, for base 3 is {0, 1, 2} and so on.

For bases starting from 11 to 36, valid digits include alphabets. The set of valid digits for base 11 is {0, 1, …, 9, A, a}, for base 12 is {0, 1, …, 9, A, a, B, b} and so on.

Example 1: How strtoull() function works?

When you run the program, the output will be:

String value = 231ax12
Unsigned Long long int value = 231
End String = ax12
String value = 231
Unsigned Long long int value = 231
Null pointer

A valid integer value for strtoull() function consists of:

  • An optional + or — sign.
  • A prefix 0 for octal base (applies only when base = 8 or 0).
  • A prefix 0x or 0X for hexadecimal base (applies only when base = 16 or 0).
  • A sequence of digits and/or alphabets (if base is greater than 10).

If the argument contains a minus (-) sign at the beginning, the negative number is implicitly converted to a unsigned long long int type which is a positive number.

The valid values for parameter base is {0, 2, 3, …, 35, 36}. A set of valid digits for base 2 is {0, 1}, for base 3 is {0, 1, 2} and so on. For bases starting from 11 to 36, valid digits include alphabets. The set of valid digits for base 11 is {0, 1, …, 9, A, a}, for base 12 is {0, 1, …, 9, A, a, B, b} and so on.

Ввод и вывод текстовой информации

Процедуры ввода — вывода символа

int ch;

ch = getch ( );- ввод кода нажатой клавиши без отображения соответствующего символа на экране

ch = getche ( );- ввод нажатой клавиши с соответствующего символа на экране

ch = getcrar ( );- ввод кода нажатой клавиши вслед за нажатием клавиши enter

Вывод символа : putchar (C1)

Процедуры ввода — вывода строки:          gets (str) , puts (str)

char str ;  // объявление строки

cout << «введите строку»;

gets (str);  // ввод строки

puts (str);  // вывод строки

Стандартные программные решения

  1. Получить символ десятичной цифры из значения переменной, лежащей в диапазоне 0…9

    int n;

    char c;

    c = n + ‘0′;

  2. Получить значение целой переменной из символа десятичной цифры

    if ( c >= ‘0’ && c <= ‘9’);

    n = c — ‘0’;

  3. Получить символ шеснадцатиричной цифры из значения целой переменной, лежащей в диапазоне 0…15

    if (n <= 9)  c = n + ‘0’;

    else  c = n- 10 + ‘A’;

  4. Преобразовать строчную латинскую букву в прописную:

     if (c >= ‘a’ && c <= ‘z’)  c = c- ‘a’ + ‘A’;

Для работы со строками необходимо использовать заголовочный файл string.h

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector