Easy Way to Convert Integer to Charecter in C

laptop coding language

Dennis Ritchie created the C programming language in 1972. The language has its roots in the B language, released in 1970. Among other software, Linux and MySQL are written in C. Because it's so simple yet so powerful, C has influenced many programming languages.

C++, for example, is a programming language derived directly from C. C is a general-purpose, structured, and procedural programming language. There are several C compilers available for converting C code to the machine language across multiple hardware platforms. System programming uses C since its programs are fast and can handle low-level tasks. The language itself has been written in assembly language.

We will examine ways to convert strings to integers (numeric values) using the C programming language in this beginner's tutorial. You should be familiar with the basics of programming.

Overview of strings in C

In the C language, a string is the type used to store any text, including alphanumeric and special characters. Internally, it's represented as an array of characters. One terminates a string in C with a NULL character, which is why they are called "null-terminated strings." To represent a string in C, enclose it in double quotes.

Internally, a string is represented in C like this, where \0 is the null character:

| T | h | i | s |  | a |  | s | t | r | i | n | g | \0 |

Many C programs use strings and associated properties. The necessary header file for string functions is string.h. The operations possible on strings include calculating the string length, concatenating multiple strings, comparing multiple strings, and copying strings. Here is an example of creating a string in C and some of its methods:

          #include <stdio.h> #include <string.h>  int main () {     char string1[12] = "Hello";    char string2[12] = "World";    char string3[12];    int  len ;     /* copies string1 into string3 */    strcpy(string3, string1);    printf("strcpy( string3, string1) :  %s\n", string3 );     /* concatenates string1 and string2 */    strcat( string1, string2);    printf("strcat( string1, string2):   %s\n", string1 );     /* total lenghth of string1 after concatenation */    len = strlen(string1);    printf("strlen(string1) :  %d\n", len );     return 0; }        

What is type conversion?

Many times in C programs, expressions contain variables and constants of different data types. For calculation purposes, they must convert to the same data type. Converting one data type to another is called type conversion.

In C, we have two types of type conversion:

  1. Implicit Type Conversion. The compiler does this automatically. Programmers don't play any role here.
  2. Explicit Type Conversion. Here the programmer is responsible for the type conversion. This is also called typecasting. The syntax is as follows:
          (datatype) expression;        

The above item is a cast operator. Take a look at this example:

          char a; int b; a = (char)b;        

This is a simple way to convert an integer to a character type. Here, "a" is of character data type and b is of integer data type. It's not possible to assign the value of variable b to variable a as they are of different data types. So, we typecast integer b to character in this example. Now, both a and b are of character data type.

How to Convert String to Integer in the C Language

Sometimes, a number is input as a string. To use it for any mathematical operation, we must convert the string to an integer. There are few ways of converting string to integer values using C:

  1. The first method is to manually convert the string into an integer with custom code.
  2. The second method is to use the atoi function included with the C standard library.
  3. The third method is using the sscanf function included in the C standard library.
  4. The fourth method uses the strtol() function included in the C standard library.
  5. The fifth method uses the strtoumax() function included in the C standard library.

Example 1: Program to manually convert a string to an integer

Below is a list of ASCII (American Standard Code for Information Interchange) characters and their decimal value.

ASCII Character Decimal Value
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57

Numbers are stored in a string by their ASCII character value. So we have to do math in order to retrieve a value we can use as an integer. In order to get the decimal value of each string element, we must subtract it with the decimal value of character "0." Here is an example to make this clearer:

          #include <stdio.h> #include <string.h>  main() {   char num[50];   int  i, len;   int result = 0;      printf("Enter a number: ");   gets(num);   len = strlen(num);  	for(i=0; i<len; i++){ 		result = result * 10 + ( num[i] - '0' ); 	}  	printf("%d", result); }        

Initially, in this program, we include stdio.h and string.h from the C standard library. This lets us use the functions that are part of these header files. The C programming language doesn't automatically include functions like these. You must import them into your software to use them.

The main function executes the C program. Hence, it's mandatory to have one in every C program. The program code is written within the curly braces of the main function.

Inside the main function we first define and declare the different variables along with their data types. Variables i, len, and result are declared as of integer data type. The result variable initializes to zero.

The printf() function is then called to display the message "enter a number" on the output screen. gets(num) will read the input number and store it as a string. In this case, the string is an array of characters pointed to by num. Then, we calculate the length of the string using the strlen() function.

Next, we loop through the string and convert the string into decimal values. Finally, the string is converted into an integer and printed on the screen.

Example 2: A program to convert a string to an integer using the atoi() function

The atoi() function converts a string data type to integer data type in the C language. The syntax of this function is:

          int atoi((const char * str);        

Here, str is of type pointer to a character. The const keyword makes variables non-modifiable. This function returns an integer value after execution. We include stdlib.h because that's where the atoi() function is. This header file contains all the type casting functions used in the C language.

          #include <stdio.h> #include <stdlib.h>  main() {   char x[10] = "450";   int result = atoi(x);   printf("integer value of the string is %d\n", result); }        

Note that the string value used with this function must be a sequence of characters interpretable as a numeric value. The function will stop reading the input once it encounters a non-numeric character. So if we changed the code above to look like this:

          #include <stdio.h> #include <stdlib.h>  main() {   char x[10] = "99x677";   int result = atoi(x);   printf("integer value of the string is %d\n", result); }        

The program above would print out: "integer value of the string is 99".

The atoi function also ignores any leading whitespace characters, but if encountered inside the string, it will stop processing the string. It will also return 0 if it can't convert the string into an integer. If there is an overflow, it will return undefined. The atoi function also doesn't recognize decimals or exponents. So you will have to write your code to account for the fact that atoi just silently fails instead of throwing an error when it can't convert a string to an integer. And the fact that the function returns a 0 when the conversion didn't work can be hard to deal with, since it's a valid integer.

Example 3: A program to convert a string to an integer using the sscanf() function

The sscanf() function acts a little differently. It reads formatted text from an input string. This is similar to the sscanf() function, but sscanf() can read data input from a string instead of the console. Here is the declaration for the sscanf() function:

          int sscanf(const char *str, const char *format, storage_variables)        

The first parameter is the string you want to parse. The second parameter is the format you want to apply to the string. You can add as many parameters that the function can take in order to store the value being read from the pointer. Here, if a regular variable stores the value instead of a pointer, then the variable name must follow the & sign.

The format parameter takes a specific type of value called a format specifier that formats the data in the string parameter in a specific way. Each format specifier character must precede the % character. Here are the format specifiers you can use:

Symbol Type
s string
c single character
d decimal integer
e, E, f, g, G floating points
u unsigned integer
x, X hexadecimal number

The bare minimum for a format specifier is the % symbol and one of the characters above. We can use either the symbol for the decimal integer or the unsigned integer, depending on what we want to accomplish. It's good to note that we can actually use this function to convert a decimal, which the atoi() function can't do. For that, we can use "%d."

But a format specifier can hold more information than that. Here is its prototype:

          [=%[*][width][modifiers]type=]        

Here we see the first character is the % symbol. The next is an optional asterisk, which indicates the data that will be read from the string but ignored. The next is the width value, which specifies the maximum amount of characters you want to read from the string.

Here is an example in code using width:

          #include <stdio.h>  int main() { 	unsigned char text[]="1234"; 	int integerValue; 	 	sscanf(text, "%04d", &integerValue); 	printf("Integer value is: %d", integerValue); 	 	return 0; }        

In the function above, we create a string containing "1234" and instantiate an integerValue variable to hold the integer we are going to parse out of the string. Next is the sscanf() function. The first parameter is our string and the last is a pointer to the integer we just instantiated. The format parameter tells the function we want to parse a decimal number from the string and that we only want four characters. The result of running it is:

Integer value is: 1234

But we can remove the width value in the format like below and get the same result:

          #include <stdio.h>  int main() { 	unsigned char text[]="1234"; 	int integerValue; 	 	sscanf(text, "%d", &integerValue); 	printf("Integer value is: %d", integerValue); 	 	return 0; }        

Example 4: A program to convert a string to an integer using the strtol() function

The C strlol() function converts a string to a long integer. This is a 64-bit integer. The standard integer is 32-bit. This is a good function to use if you expect to be converting strings that contain long numbers. It functions similarly to the atoi() function. It ignores any whitespace at the beginning of a string, but it will stop processing the string when it encounters a whitespace or any other non-digit in the string.

Here is the syntax of the strlol() function:

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

The first parameter is a pointer to the string that you want to convert. The second parameter is a pointer used by the function that points to the first non-integer character the function runs into when it stops processing. The final parameter is the base of the number being converted. It can be a number between 2 and 32 or a special value of 0.

Here is a program that will convert a string into a long integer:

          #include <stdio.h> #include <stdlib.h> #include <string.h>  int main() {     char str[10];     char *ptr;     long value;          strcpy(str, " 12345");     value = strtol(str, &ptr, 10);     printf("the long integer value is %ld\n", value);      return 0; }        

In the beginning of the main function above, we instantiate the three variables we are going to need to demonstrate the strlol() function: a string, a pointer, and a long integer. Then we set the value of our string to " 12345″ with a leading space to demonstrate that the function will strip leading white space. Then we pass the string and the pointer to strlol() along with 10 as the last parameter because we are parsing decimal numbers that have a base of 10. The result of the function is:

the long integer value is 12345

Example 5: A program to convert a string to an integer using the strtoumax() function

The C strtoumax() is very similar to the strlol() function, but they return intmax_t value, which is the largest possible integer type in C. Its syntax is even the same:

          long int strtoumax(const char *str, char **endptr, int base);        

And here is an example using the strtoumax function:

          #include <stdio.h> #include <stdlib.h>  int main() {   char int[10] = " 98765", *end;      unsigned long x = strtoumax(int, &end, 10);   printf("the integer value is %ld\n", x);      return 0; }        

This function is similar to the one we wrote for the strlol() function. Here is the result of this program:

the integer value is 98765

Even more ways to convert a string to an integer in C

These aren't the only functions you can use in C to convert strings to integers. It really is a flexible language and gives you a lot to choose from. Here are those other functions:

  • strtoul: Same as strtol, but it works with unsigned integers instead of signed integers.
  • wcstoul: Same as the strtoul function, but it handles wide character strings.
  • strtoll: Similar to strtol except it returns a long long int value and accepts numbers with a larger range.
  • wcstoll: Similar to stroll, but it handles wide character strings.
  • strtoimax: Similar to strtoumax, but it works with signed instead of unsigned integers.

Conclusion

Even if there is numerical value in a string, you can't perform any calculations on it in the C programming language unless you convert it to an integer first. Fortunately, there are a lot of ways to do this with the C standard library. You can write your own function or use one of the many built-in conversion functions that come with C. Each function converts integers slightly differently, so which you use depends on the size of the integer you will be parsing and what you will do with it.

ruizbeading.blogspot.com

Source: https://blog.udemy.com/c-string-to-int/

0 Response to "Easy Way to Convert Integer to Charecter in C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel