Atoi c что это
Feature Test Macro Requirements for glibc (see feature_test_macros (7)):
atoll (): _BSD_SOURCE || _SVID_SOURCE || _XOPEN_SOURCE >= 600 || _ISOC99_SOURCE || _POSIX_C_SOURCE >= 200112L;
or cc -std=c99
DESCRIPTION
strtol(nptr, NULL, 10);
except that atoi () does not detect errors.
The atol () and atoll () functions behave the same as atoi (), except that they convert the initial portion of the string to their return type of long or long long .
Функция 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.
Convert String to int in C
Converting string to int is a reoccurring task in the programming world. Despite being a simple task, many coders either fail or get confused while doing this. Conversion is mostly done so that we can perform operations over numbers that are stored as strings.
Example:
C is a strongly typed language. We’ll get an error if we try to input a value that isn’t acceptable with the data type. Not just in inputs but we will get an error while performing operations.
There are 3 methods to convert a string to int which are as follows:
- Using atoi( )
- Using Loops
- Using sscanf()
1. String Conversion using atoi( )
The atoi() function in C takes a character array or string literal as an argument and returns its value in an integer. It is defined in the <stdlib.h> header file.
If you observe atoi() a little closer you will find out that it stands for:

Breakdown of atoi() in simple terms
Example:
Atoi behaves a bit differently for string. Let’s check how:
Example:
Explanation:
- “Geek 12345” here ‘Geek’ is the first word so the answer will be : 0 (No number)
- “12345 Geek” here ‘12345’ is the first word so the answer will be: 12345
2. Using Loops
We can use loops to convert a string to an integer by traversing each element of the string one by one and comparing the number characters to their ASCII values to get their numeric values and using some mathematics for generating the integer. The below example demonstrates how to do it.
Example:
Note: We have used str[i] – 48 to convert the number character to their numeric values. For e.g. ASCII value of character ‘5’ is 53, so 53 – 48 = 5 which is its numeric value.
3. Using sscanf()
We can use sscanf() to easily convert a string to an integer. This function reads the formatted input from the string.
Syntax of sscanf:
Parameters:
- source – source string.
- formatted_string – a string that contains the format specifiers.
- … : – variable arguments list that contains the address of the variables in which we want to store input data.
There should be at least as many of these arguments as the number of values stored by the format specifiers. On success, the function returns the number of variables filled. In the case of an input failure, before any data could be successfully read, EOF is returned.