C Convert String to Int and Back Again
Dennis Ritchie created the C programming linguistic communication in 1972. The language has its roots in the B linguistic communication, released in 1970. Among other software, Linux and MySQL are written in C. Because it's so unproblematic notwithstanding so powerful, C has influenced many programming languages.
C++, for instance, is a programming linguistic communication 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 linguistic communication across multiple hardware platforms. Arrangement programming uses C since its programs are fast and can handle depression-level tasks. The language itself has been written in assembly language.
We volition examine ways to catechumen strings to integers (numeric values) using the C programming language in this beginner's tutorial. You lot 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 whatsoever 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 chosen "cypher-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 nada character:
| T | h | i | s | | a | | s | t | r | i | north | one thousand | \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 cord length, concatenating multiple strings, comparing multiple strings, and copying strings. Here is an instance of creating a string in C and some of its methods:
#include <stdio.h> #include <string.h> int primary () { char string1[12] = "How-do-you-do"; 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 ); /* full lenghth of string1 after chain */ 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 information types. For calculation purposes, they must catechumen to the aforementioned data type. Converting one data type to another is called blazon conversion.
In C, we accept ii types of type conversion:
- Implicit Type Conversion. The compiler does this automatically. Programmers don't play any role here.
- Explicit Type Conversion. Hither the programmer is responsible for the blazon conversion. This is likewise called typecasting. The syntax is as follows:
(datatype) expression;
The above detail is a cast operator. Take a look at this example:
char a; int b; a = (char)b;
This is a simple way to catechumen an integer to a character blazon. Hither, "a" is of character data type and b is of integer data type. It'due south not possible to assign the value of variable b to variable a as they are of different data types. Then, we typecast integer b to grapheme in this example. Now, both a and b are of graphic symbol data blazon.
How to Convert String to Integer in the C Language
Sometimes, a number is input every bit a string. To utilize it for whatsoever mathematical operation, we must convert the cord to an integer. There are few ways of converting string to integer values using C:
- The first method is to manually catechumen the string into an integer with custom lawmaking.
- The 2d method is to use the atoi function included with the C standard library.
- The 3rd method is using the sscanf part included in the C standard library.
- The fourth method uses the strtol() function included in the C standard library.
- The 5th method uses the strtoumax() office included in the C standard library.
Example 1: Programme to manually catechumen a cord 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 |
v | 53 |
6 | 54 |
7 | 55 |
eight | 56 |
ix | 57 |
Numbers are stored in a string by their ASCII character value. And so we have to do math in order to think a value nosotros tin 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." Hither is an example to brand this clearer:
#include <stdio.h> #include <string.h> chief() { char num[50]; int i, len; int result = 0; printf("Enter a number: "); gets(num); len = strlen(num); for(i=0; i<len; i++){ outcome = result * x + ( 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 similar these. You must import them into your software to use them.
The chief function executes the C program. Hence, it's mandatory to have one in every C program. The programme code is written within the curly braces of the primary function.
Inside the main role we first define and declare the dissimilar variables along with their data types. Variables i, len, and result are declared as of integer data blazon. The effect variable initializes to zero.
The printf() part is and then chosen 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. And so, we calculate the length of the string using the strlen() function.
Next, we loop through the cord and convert the string into decimal values. Finally, the cord is converted into an integer and printed on the screen.
Case 2: A program to convert a string to an integer using the atoi() part
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 arrow to a graphic symbol. The const keyword makes variables non-modifiable. This office 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 linguistic communication.
#include <stdio.h> #include <stdlib.h> main() { char x[10] = "450"; int result = atoi(x); printf("integer value of the string is %d\n", issue); }
Notation that the cord value used with this function must be a sequence of characters interpretable equally a numeric value. The office volition end reading the input once it encounters a non-numeric character. So if nosotros changed the code higher up to wait 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 impress out: "integer value of the cord is 99".
The atoi function also ignores whatever leading whitespace characters, only if encountered inside the string, it volition stop processing the string. Information technology will also return 0 if information technology can't convert the string into an integer. If there is an overflow, information technology will return undefined. The atoi role also doesn't recognize decimals or exponents. And then y'all will take to write your code to account for the fact that atoi just silently fails instead of throwing an error when it can't catechumen a string to an integer. And the fact that the part returns a 0 when the conversion didn't work can be difficult to bargain with, since it'due south a valid integer.
Example 3: A plan to catechumen a cord to an integer using the sscanf() part
The sscanf() function acts a piffling differently. Information technology reads formatted text from an input string. This is similar to the sscanf() office, simply sscanf() can read information input from a string instead of the console. Here is the declaration for the sscanf() part:
int sscanf(const char *str, const char *format, storage_variables)
The first parameter is the string you desire to parse. The second parameter is the format you want to apply to the cord. You can add as many parameters that the function can accept in order to store the value being read from the arrow. 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 blazon of value called a format specifier that formats the data in the cord parameter in a specific way. Each format specifier grapheme must precede the % character. Here are the format specifiers you lot tin can use:
Symbol | Type |
south | cord |
c | single character |
d | decimal integer |
e, Due east, f, g, G | floating points |
u | unsigned integer |
10, X | hexadecimal number |
The bare minimum for a format specifier is the % symbol and one of the characters above. We tin utilise either the symbol for the decimal integer or the unsigned integer, depending on what nosotros want to accomplish. Information technology'south good to notation that we tin actually apply this part to convert a decimal, which the atoi() role can't do. For that, nosotros can utilise "%d."
But a format specifier can hold more than data than that. Hither is its prototype:
[=%[*][width][modifiers]blazon=]
Hither we meet the first grapheme is the % symbol. The side by side 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 yous want to read from the string.
Here is an example in code using width:
#include <stdio.h> int master() { unsigned char text[]="1234"; int integerValue; sscanf(text, "%04d", &integerValue); printf("Integer value is: %d", integerValue); return 0; }
In the part above, nosotros 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() part. The first parameter is our string and the terminal is a arrow 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 simply want iv characters. The outcome of running it is:
Integer value is: 1234
But we can remove the width value in the format like below and get the aforementioned 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() part 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 cord, just it will end processing the cord 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 beginning parameter is a pointer to the string that you want to catechumen. The second parameter is a pointer used by the function that points to the beginning non-integer character the function runs into when it stops processing. The last parameter is the base of the number being converted. It can be a number between 2 and 32 or a special value of 0.
Hither is a program that volition convert a string into a long integer:
#include <stdio.h> #include <stdlib.h> #include <cord.h> int main() { char str[ten]; 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, nosotros instantiate the three variables we are going to need to demonstrate the strlol() part: a string, a pointer, and a long integer. Then nosotros fix the value of our string to " 12345″ with a leading space to demonstrate that the role will strip leading white infinite. Then we laissez passer the string and the pointer to strlol() forth with 10 as the last parameter because we are parsing decimal numbers that have a base of 10. The result of the office is:
the long integer value is 12345
Example 5: A plan to convert a cord 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 part:
#include <stdio.h> #include <stdlib.h> int principal() { char int[ten] = " 98765", *end; unsigned long x = strtoumax(int, &end, ten); printf("the integer value is %ld\n", x); return 0; }
This function is similar to the one we wrote for the strlol() role. Here is the result of this program:
the integer value is 98765
Fifty-fifty more means to catechumen a string to an integer in C
These aren't the but functions you tin use in C to convert strings to integers. It really is a flexible linguistic communication and gives you a lot to choose from. Hither are those other functions:
- strtoul: Same as strtol, simply it works with unsigned integers instead of signed integers.
- wcstoul: Same as the strtoul function, but information technology handles broad character strings.
- strtoll: Like 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: Like to strtoumax, only it works with signed instead of unsigned integers.
Decision
Even if there is numerical value in a string, y'all can't perform any calculations on it in the C programming language unless yous convert information technology to an integer outset. Fortunately, there are a lot of ways to do this with the C standard library. Y'all tin write your own function or utilize one of the many built-in conversion functions that come up with C. Each office converts integers slightly differently, and so which you utilize depends on the size of the integer you will be parsing and what you will practice with it.
wellsbrieforetwor.blogspot.com
Source: https://blog.udemy.com/c-string-to-int/
0 Response to "C Convert String to Int and Back Again"
Post a Comment