Как преобразовать число в строку в си
Нередко в программах встречается ситуация, когда надо преобразовать число в строку или строку в число. Для этой цели в стандартной библиотеке языка С определены функции strtol() и snprintf() .
Из строки в число. strtol
Функция strtol() преобразует строку в число типа long int . Функция определена в заголовочном файле stdlib.h и имеет следующий прототип:
str — строка с числом, которое надо преобразовать в числовой тип. Ключевое слово restrict указывает компилятору оптимизировать код и что никакой другой параметр не будет указывать на адрес данного параметра.
str_end — указатель на последний символ строки. Данный параметр можно игнорировать, передавая ему значение NULL
base — основание, система исчисления, в которую надо преобразовать данные (значение от 2 до 36).
Результатом функции является преобразованное число типа long .
Например, преобразуем строку в число в десятичной системе:
В примере выше второй параметр функции никак не использовался — мы ему передавали значение NULL , и функция нормально работала. Однако он может быть полезен, если нам надо получить остаток строки, которая идет после числа:
Из числа в строку. snprintf
Функция snprintf() преобразует число в отформатированную строку. Функция определена в заголовочном файле stdio.h и имеет следующий прототип:
str_buffer — строка, в которую помещается преобразованное число.
buffer_size — максимальное количество символов строки. Функция записывает в строку buffer-size — 1 байт и добавляет концевой нулевой байт
format — задает формат преобразования в строку.
При успешном преобразовании функция возвращает количество символов, записанных в строку (исключая концевой нулевой байт). При неудачном преобразовании возвращается отрицательное число.
Convert an Integer to a String in C
This tutorial introduces how to convert an integer to a string value in C. There are different methods for converting an integer to a string in C, like the sprintf() and itoa() functions.
sprintf() Function to Convert an Integer to a String in C
As its name suggests, it prints any value into a string. This function gives an easy way to convert an integer to a string. It works the same as the printf() function, but it does not print a value directly on the console but returns a formatted string. The return value is usually discarded, but if an error occurs during the operation, it returns -1 .
sprintf() Syntax:
- str is a pointer to a char data type.
- format is is used to display the type of output along with the placeholder.
- arg1 , arg2 are integers to convert into a string.
Example Code of sprintf() to Convert an Integer to a String in C
itoa() Function to Convert an Integer to a String in C
itoa() is a type casting function in C. This function converts an integer to a null-terminated string. It can also convert a negative number.
How to Convert int to string in C
The C library sprintf() function allows us to convert integers into a formatted string. In this example, we are going to make use of the sprintf() function from the C standard library. This function is just like a format specifier that takes the format in which we want to print the input.
Syntax
Parameters
- str: is a pointer to char str in which we will get output.
- formatspec : is used to specify the format which we want for output.
- arg1, arg2 are integers to convert into a string.
Return Value
If the conversion is successful It returns the length of converted to number to string else negative value is a return.
1.2 Program sprint() to convert int to string in C
In this C Program, we have taken a number input from the user and mystr is an empty buffer of type string. We are using the sprint function to convert the input number to a string. Finally, use the printf() function to print the output on the console.
Syntax
Parameters
- str = is a pointer to a char str in which we will get output.
- formatspec = is is used to specify the format which we want for output.
- arg1, arg2 are integers to convert into a string.
C Program to Convert an Integer to a String using sprintf()
2. Convert int to string in C Using itoa() function
The itoa() C function allows us to convert integer numbers into null-terminated strings. In this example, we are going to make use of the itoa() function. This function can be used by just including the header file in your program. This function accepts an integer and returns a null-terminated string.
Note:- This function is not a standard function and on the Linux Posix system it may not work. It will work on windows systems for sure.
Syntax
Parmeters
- val: The integer number need to convert into string.
- str : It is a character array and pointer to buffer in memory where null terminated result string will store.
- Base : The base is a numeric value range from 2 to 32 categories as below
- binary : if base is 2
- octal : if base is 8
- Decimal: if base is 10
- Hex : base is 16
2.1 Using itoa() function to convert int to string in C
In this example, we are using itoa() function to convert int to string. This function is not defined in ANSI-C. But some compilers support it.
C Program to Convert an Integer to a String in C by using itoa() Function
Summary
In this post we have learned how to convert int to string in C by using the following ways: