Функция atoi
Функция atoi преобразует строку string в целое значение типа int . Анализируя строку string , atoi интерпретирует её содержание, как целое число, которое возвращается как int .
Функция сначала отбрасывает символы пробелов до тех пор, пока не будет найден символ отличный от нуля. Затем, начиная с этого символа, функция принимает необязательный начальный знак плюс или минус. После чего, следует последовательность цифр, которая интерпретируется в числовое значение.
Строка может содержать другие символы после считанного целого числа, эти символы игнорируются и никак не влияют на поведение этой функции.
Если первая последовательность не-пробельных символов в строке string не является целым числом, или, если string пустая или содержит только пробельные символы, преобразование не выполняется.
Параметры:
- string
Строка для преобразования в целое число.
Возвращаемое значение
В случае успеха, функция возвращает целое число преобразованное к типу int .
Если в строке не было найдено целое число, функция возвращает нулевое значение.
Существует не стандартная ситуация, когда преобразованное значение выйдет из диапазона принимаемых значений типа данных int . Поэтому, предусмотрена более надежная кросс-платформенная альтернатива — функция strtol .
Atoi c что это
Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int .
The function first discards as many whitespace characters (as in isspace ) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.
Parameters
Return Value
Example
Data races
Exceptions (C++)
No-throw guarantee: this function never throws exceptions.
If str does not point to a valid C-string, or if the converted value would be out of the range of values representable by an int , it causes undefined behavior.
C Language: atoi function
(Convert String to Integer)
In the C Programming Language, the atoi function converts a string to an integer.
The atoi function skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn’t a number.
Syntax
The syntax for the atoi function in the C Language is:
Parameters or Arguments
Returns
The atoi function returns the integer representation of a string. The atoi function skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn’t a number.
Required Header
In the C Language, the required header for the atoi function is:
Applies To
In the C Language, the atoi function can be used in the following versions:
- ANSI/ISO 9899-1990
Similar Functions
Other C functions that are similar to the atoi function:
See Also
Other C functions that are noteworthy when dealing with the atoi function:
std:: atoi, std:: atol, std:: atoll
Interprets an integer value in a byte string pointed to by str . The implied radix is always 10.
Discards any whitespace characters until the first non-whitespace character is found, then takes as many characters as possible to form a valid integer number representation and converts them to an integer value. The valid integer value consists of the following parts:
- (optional) plus or minus sign
- numeric digits
If the value of the result cannot be represented, i.e. the converted value falls out of range of the corresponding return type, the behavior is undefined.
Contents
[edit] Parameters
| str | — | pointer to the null-terminated byte string to be interpreted |
[edit] Return value
Integer value corresponding to the contents of str on success.
If no conversion can be performed, 0 is returned.
[edit] Possible implementation
Actual C++ library implementations fall back to C library implementations of atoi , atoil , and atoll , which either implement it directly (as in MUSL libc) or delegate to strtol / strtoll (as in GNU libc).