C как конвертировать string в long

от admin

Convert String to Long in C

By default, the compiler inserts a null character to the completion of a series of elements surrounded by inverted commas. The long data type retains integers the same way int does, but it has a larger range of possibilities when using additional memory. The strtol() method has been used to modify an integer’s string illustration to a long type. It is declared in the header file <stdlib.h>. It’s much more versatile and efficient than the atol() method.

The strtol() method allows the user to set the value of the string’s base. This method would be used to translate any string to a long type. We may immediately differentiate between effective and ineffective transformations by the strtol() method. In this article, we’ll explore how to transform a string to a long, while utilizing multiple C functions.

Use the strtol() Function to Change the String to Long

The strtol() is a C library method of transforming the first portion of a string to a long data type value based on the specified base, which needs to be between 2 and 36 encompassing or the exceptional value 0.

The strtol() method requires three arguments: a defined string, a pointer, and a numeric value base. It translates the string’s data as an integrated part of the provided base and produces a long int value.

int main ( ) {
char s [ 40 ] = "304852 Information Technology" ;
char * p ;
long res ;
res = strtol ( s , & p , 10 ) ;
printf ( "The number is %ld \n " , res ) ;
printf ( "String portion is |%s|" , p ) ;
return ( 0 ) ;
}

We are going to start the program by integrating two libraries: <stdio.h> and <stdlib.h>. In the next step, we utilize the main() function. Within the main() function, a string having a character data type is defined. Here, we set the size of the defined string. This string contains both numeric and alphabetic portions.

Further, we declare a pointer and a variable “long res” for storing the result. Now, we apply the strtol() function. This method contains three arguments. The first parameter shows the integral portion of the defined string. The second argument is the pointer to a character object that has already been created.

The function specifies the valuation of the end toward the next valid character in the string and followed by the previous suitable character. And the last parameter represents the base of the numeric part. The range of acceptable base values is 0, 2, 3… 35, 36. Hence, the printf() method first prints the numeric portion and then prints the string portion.

Use the strtol() Function for Preceding Spacing With Different Bases

Until the initial non-whitespace element is detected, the strtol() method avoids any preceding whitespace elements. This function transforms the string to a long int value and takes many of the elements as necessary that create a suitable integer illustration. Since the last definitive character, anything left on the line is eliminated and has no impact on the outcome.

using namespace std ;
int main ( )
{
char * e ;
printf ( "40lmno to Long Integer having base-13 = %d \n " ) ;
strtol ( "40lmno" , & e , 13 ) ;
printf ( "String = %s" , e ) ;
printf ( "13674di to Long Integer having base-6 = %d \n " ) ;
strtol ( "13674di" , & e , 6 ) ;
printf ( "String = %s" , e ) ;
printf ( "pqt589.2 to Long Integer having base-20 = %d \n " ) ;
strtol ( "pqt589.2" , & e , 20 ) ;
printf ( "String = %s" , e ) ;
return 0 ;
}

Here, we introduce two header files <stdlib.h> and <cstdlib>. After this, we utilize the standard namespace function. Further, the body of the main() function starts. Meanwhile, we construct the pointer of the character data type. Now, we apply the printf() function for displaying the defined line.

In addition, the strtol() function is also applied. This function contains the required string, pointer, and the base to which the string has to be converted as parameters. In the next step, the printf() function is again used to display the converted string. Similarly, we employ the strtol() function and set the base to 6 and 20. Printf() method is also used to get the results of these conversions. To terminate the program, we have to include the following “return 0” statement:

Use the atol() Function to Convert the String to Long

An alphanumeric string is changed to a long value using the atol() method. The corresponding string is a series of bits that could be translated into an integer value of the data type provided. The method refuses to read the entered string once it detects the first character and doesn’t identify it as an integer. This might be the invalid character at the termination of the string.

Читать:
Как получить код символа в си

The atol() method generates a long value by converting the specified characters into integers. If the function is unable to transform the data to a variable of that type, it gives 0L. In the situation of overload, the return type is invalid.

At the start of the code, we have to include the required header files, <stdlib.h> and <stdio.h>. Now, we employ the main() function. In the next step, we declare a variable having a long data type and a pointer for the string which has a character data type. Next, we specify the value of the string in dollars.

In addition to this, the atol() method is called. Here, we passed the required string as a parameter to this function. The atol() function converts the string to long. In the end, we utilize the printf() function to display the result.

Conclusion

In this article, we have observed the methods of converting the string to long in C language. Here, we have gone through the use of the strtol() function and atol() function for this type of conversion. We have also utilized the strtol() method having different bases for converting string to long. We hope you found this article helpful. Check the other Linux Hint articles for more tips and tutorials.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content

C Language: strtoll function
(Convert String to Long Long)

In the C Programming Language, the strtoll function converts a string to a long long.

The strtoll 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 strtoll function in the C Language is:

Parameters or Arguments

Returns

The strtoll function returns the long long representation of a string. The strtoll 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.

If the strtoll function converts a value that is too large or too small to convert, it will store ERANGE in errono. If the value is too large to convert, the function will return a value of LLONG_MAX. If the value is too small to convert the function will return a value of LLONG_MIN.

Required Header

In the C Language, the required header for the strtoll function is:

Applies To

In the C Language, the strtoll function can be used in the following versions:

  • ANSI/ISO 9899-1990

strtoll Example

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

When compiled and run, this application will output:

Similar Functions

Other C functions that are similar to the strtoll function:

See Also

Other C functions that are noteworthy when dealing with the strtoll function:

Как я мог преобразовать данные из строки в длинные в с #

Как я могу преобразовать данные из строки в длинные в C #?

У меня есть данные

теперь я хочу это в

задан 13 июн ’11, 09:06

Длинные числа представляют собой целые числа. Вы указали нецелое число. Что бы вы хотели с этим делать? — Jon Skeet

@magma: если вы конвертируете его в десятичное число, оно округлит число, т.е. в этом случае, если заданное число было 1100.75, оно выведет 1101. — love Computer science

@charlie Я просто поднял вопрос, потому что MayP, похоже, не полностью осознавал значение этого. Он может захотеть просто избавиться от нецелой части без округления, и это нормально, при условии, что это действительно то, что он хочет. Однако, спасибо. — magma

9 ответы

Этот ответ больше не работает, и я не могу придумать ничего лучше, чем другие ответы (см. Ниже), перечисленные здесь. Просмотрите их и проголосуйте за них.

C как конвертировать string в long

Here, we will see how to build a C Program For String to Long Conversion using strtol() function.

Syntax:

  1. The first argument is given as a string
  2. The second argument is a reference to an object of type char*
  3. The third argument denotes the base in which the number is represented. To know more about visit strtol() function.

Note: We don’t have to use long int in the case of strtoul() because the range of unsigned long is greater than long on the positive front.
[long : -2147483648 to 2147483647 and unsigned long : 0 to 4294967295]

Syntax:
strtoul(char *string, char **ptr, int base) // no long int need in strtoul()

Похожие статьи