C Convert String to Int and Back Again
Dennis Ritchie created the C programming language in 1972. The linguistic communication has its roots in the B linguistic communication, released in 1970. Amongst other software, Linux and MySQL are written in C. Considering information technology'southward then unproblematic nevertheless so powerful, C has influenced many programming languages.
C++, for example, is a programming language derived straight from C. C is a general-purpose, structured, and procedural programming language. There are several C compilers bachelor for converting C code to the auto linguistic communication 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.
Nosotros will examine ways to convert strings to integers (numeric values) using the C programming language in this beginner's tutorial. You should exist familiar with the basics of programming.
Overview of strings in C
In the C linguistic communication, a string is the type used to shop 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 "naught-terminated strings." To stand for a string in C, enclose it in double quotes.
Internally, a string is represented in C similar this, where \0 is the cipher character:
| T | h | i | s | | a | | s | t | r | i | north | m | \0 |
Many C programs use strings and associated backdrop. The necessary header file for string functions is string.h. The operations possible on strings include computing the string length, concatenating multiple strings, comparing multiple strings, and copying strings. Here is an instance of creating a cord in C and some of its methods:
#include <stdio.h> #include <string.h> int main () { char string1[12] = "Hi"; 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): %southward\northward", 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 incorporate variables and constants of different data types. For adding purposes, they must convert to the same information blazon. Converting one data type to another is called type conversion.
In C, we accept two types of blazon conversion:
- Implicit Blazon Conversion. The compiler does this automatically. Programmers don't play whatsoever role here.
- Explicit Type Conversion. Here the programmer is responsible for the blazon conversion. This is as well called typecasting. The syntax is as follows:
(datatype) expression; The in a higher place item is a cast operator. Take a await at this instance:
char a; int b; a = (char)b; This is a simple way to convert an integer to a character type. Here, "a" is of graphic symbol data type and b is of integer data type. Information technology'due south not possible to assign the value of variable b to variable a equally they are of different data types. And so, we typecast integer b to graphic symbol in this example. At present, both a and b are of character information type.
How to Convert String to Integer in the C Linguistic communication
Sometimes, a number is input as a string. To use it for any mathematical operation, we must convert the string to an integer. In that location are few ways of converting string to integer values using C:
- The first method is to manually convert the string into an integer with custom code.
- The second method is to employ the atoi function included with the C standard library.
- The 3rd method is using the sscanf function included in the C standard library.
- The fourth method uses the strtol() function included in the C standard library.
- The fifth method uses the strtoumax() function included in the C standard library.
Instance 1: Programme 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 |
| two | 50 |
| three | 51 |
| iv | 52 |
| 5 | 53 |
| 6 | 54 |
| 7 | 55 |
| 8 | 56 |
| 9 | 57 |
Numbers are stored in a string by their ASCII grapheme value. So we accept to do math in order to call back a value we can apply as an integer. In order to get the decimal value of each cord chemical element, we must subtract it with the decimal value of character "0." Here is an case 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 * ten + ( num[i] - '0' ); } printf("%d", result); } Initially, in this plan, we include stdio.h and string.h from the C standard library. This lets us use the functions that are role 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.
Within the main role we first ascertain and declare the unlike variables along with their data types. Variables i, len, and effect are declared every bit of integer information type. The upshot variable initializes to aught.
The printf() function is so 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 assortment of characters pointed to by num. And so, we calculate the length of the cord using the strlen() role.
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 plan to convert a string to an integer using the atoi() office
The atoi() role converts a cord data blazon to integer data type in the C language. The syntax of this function is:
int atoi((const char * str); Here, str is of blazon pointer to a character. The const keyword makes variables non-modifiable. This function returns an integer value after execution. Nosotros include stdlib.h considering that's where the atoi() office 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 cord is %d\n", issue); } Note that the string value used with this part must be a sequence of characters interpretable equally a numeric value. The role volition terminate reading the input one time it encounters a non-numeric character. So if we changed the lawmaking higher up to look like this:
#include <stdio.h> #include <stdlib.h> main() { char x[10] = "99x677"; int result = atoi(10); printf("integer value of the string is %d\n", outcome); } The plan above would impress out: "integer value of the string is 99".
The atoi function also ignores whatever leading whitespace characters, only if encountered within the string, it will end processing the cord. It will too 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 take to write your lawmaking to account for the fact that atoi just silently fails instead of throwing an error when information technology can't convert a string to an integer. And the fact that the office returns a 0 when the conversion didn't work can be hard to deal with, since information technology'south a valid integer.
Case 3: A program to convert a cord to an integer using the sscanf() office
The sscanf() function acts a picayune differently. It reads formatted text from an input string. This is similar to the sscanf() function, merely sscanf() can read data input from a cord instead of the console. Here is the proclamation for the sscanf() function:
int sscanf(const char *str, const char *format, storage_variables) The first parameter is the string y'all want to parse. The second parameter is the format you lot want to employ to the string. Yous tin can add every bit many parameters that the function tin accept in lodge to store the value being read from the arrow. Here, if a regular variable stores the value instead of a pointer, then the variable proper 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 style. Each format specifier character must precede the % grapheme. Here are the format specifiers you tin utilise:
| Symbol | Blazon |
| s | string |
| c | single grapheme |
| d | decimal integer |
| e, Due east, 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 desire to accomplish. It'southward adept to note that we can actually use this function to catechumen a decimal, which the atoi() role can't do. For that, we tin apply "%d."
But a format specifier can hold more than data than that. Here is its epitome:
[=%[*][width][modifiers]type=] Here we come across the offset character is the % symbol. The next is an optional asterisk, which indicates the data that volition be read from the cord only ignored. The adjacent is the width value, which specifies the maximum amount of characters you want to read from the string.
Hither 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 in a higher place, 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() office. The first parameter is our string and the concluding is a pointer to the integer nosotros just instantiated. The format parameter tells the office we want to parse a decimal number from the string and that we only desire four characters. The effect of running it is:
Integer value is: 1234
Merely we tin remove the width value in the format similar beneath and get the same result:
#include <stdio.h> int principal() { unsigned char text[]="1234"; int integerValue; sscanf(text, "%d", &integerValue); printf("Integer value is: %d", integerValue); return 0; } Case iv: A program to convert a cord to an integer using the strtol() function
The C strlol() function converts a string to a long integer. This is a 64-chip integer. The standard integer is 32-flake. This is a skilful function to use if you await to be converting strings that contain long numbers. It functions similarly to the atoi() function. It ignores any whitespace at the commencement of a string, but information technology will stop processing the cord when information technology encounters a whitespace or any other non-digit in the string.
Here is the syntax of the strlol() office:
long int strtol(const char *str, char **endptr, int base); The first parameter is a pointer to the cord that y'all desire to catechumen. The 2d parameter is a pointer used by the function that points to the first non-integer graphic symbol the function runs into when it stops processing. The last parameter is the base of the number beingness converted. It can be a number betwixt 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 primary() { char str[10]; char *ptr; long value; strcpy(str, " 12345"); value = strtol(str, &ptr, x); printf("the long integer value is %ld\n", value); render 0; } In the starting time of the main function in a higher place, we instantiate the iii variables we are going to need to demonstrate the strlol() function: a cord, a pointer, and a long integer. Then we set up the value of our string to " 12345″ with a leading infinite to demonstrate that the office will strip leading white infinite. Then we pass the cord and the pointer to strlol() along with ten as the terminal parameter considering we are parsing decimal numbers that have a base of 10. The consequence of the function is:
the long integer value is 12345
Case 5: A program to convert a string to an integer using the strtoumax() function
The C strtoumax() is very similar to the strlol() function, only 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 of operations); And here is an example using the strtoumax function:
#include <stdio.h> #include <stdlib.h> int main() { char int[x] = " 98765", *end; unsigned long x = strtoumax(int, &terminate, 10); printf("the integer value is %ld\north", 10); return 0; } This function is similar to the one we wrote for the strlol() function. Hither is the result of this program:
the integer value is 98765
Fifty-fifty more ways to convert a string to an integer in C
These aren't the only functions you tin use in C to convert strings to integers. Information technology really is a flexible language and gives you lot 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: Aforementioned as the strtoul role, just information technology 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 information technology handles wide character strings.
- strtoimax: Similar to strtoumax, merely 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 y'all convert it to an integer first. Fortunately, at that place are a lot of means to practice this with the C standard library. Yous tin write your own function or use 1 of the many built-in conversion functions that come up with C. Each function converts integers slightly differently, so which you employ depends on the size of the integer you volition exist parsing and what yous will do with information technology.
Source: https://blog.udemy.com/c-string-to-int/
Post a Comment for "C Convert String to Int and Back Again"