In programming, there are many instances where you need to convert strings to numbers.Operating systems, embedded devices, and other applications can all be created using the well-liked programming language C.
While dealing with user input or data from files, you may often encounter string data that needs to be converted to numbers for further processing.
This article explains how to convert string to number in C and provides different methods to do so.
Why Is There A Need for Converting From String To Number In C
Here are the reasons for the need of conversion in C:
- User input: When a user enters data through the keyboard or other input devices, the input is generally in string format. To use this data in numerical calculations or comparisons, you need to convert it to a number format.
- Data storage: Sometimes data is stored in a file or a database as a string. This method is used when storing data to be converted to a specific type of number, such as a float or double.
- Data manipulation: In some cases, you may need to manipulate data in string format, such as trimming or splitting a string. To perform this on this data, you need to convert it to a numerical format.
- Compatibility: Some libraries or functions in C require numerical data as input. To use these libraries or functions the data should be in numerical format.
- Error handling: If the input data is not in the correct format, your program may produce unexpected results or crash. By converting string data to a numerical format, you can perform error checking and handling to ensure that your program runs correctly.
Approaches on how to convert string to number in c
There are various approaches to converting a string to a number in C. Here are some of the commonly used methods:
- Approach -1: Using the atoi() Function
- Approach -2: Using the strtol() Function
- Approach -3: Using the sscanf() Function
- Approach -4: Using the strtol() Function with Base Parameter
Approach -1: How to convert string to number in c Using the atoi() Function
The atoi() function in C can be used to convert a string to an integer. This method is simple and straightforward.
Algorithm:
Step 1: Include the header file stdlib.h to use the atoi() function.
Step 2: Declare a string variable to store the input string.
Step 3: Use the scanf() function to read the input string from the user.
Step 4: Use the atoi() function to convert the input string to an output integer.
Step 5: Display the converted integer using the printf() function.
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[10];
int num;
printf("Enter a number as string: ");
scanf("%s", str);
num = atoi(str);
printf("The converted integer is %d\n", num);
return 0;
}
Output:
Enter a number as string: 123
The converted integer is 123
Code Explanation:
- The code includes two header files: <stdio.h> and <stdlib.h>.
- The main() function is declared, which is the entry point of the program.
- Two variables are declared within the main() function: a character array str of size 10 and an integer variable num.
- The printf() function is used to display a message on the screen asking the user to enter a number as a string.
- The scanf() function is used to take user input from the keyboard and store it in the str variable.
- The atoi() function is called, which converts the string stored in str to an integer and stores it in the num variable.
- The printf() function is used again to display the converted integer on the screen.
- Finally, the main() function returns 0, which indicates that the program has executed successfully.
Approach-2: How to convert string to number in c Using the strtol() Function
The strtol() function in C can be used to convert a string to a long integer. It provides more control over the conversion process and can handle errors more effectively than the atoi() function. This method is useful when you need to perform error handling or deal with input strings of different bases.
Algorithm:
Step 1: Include the header file stdlib.h to use the strtol() function.
Step 2: Declare a string variable to store the input string.
Step 3: Use the scanf() function to read the input string from the user.
Step 4: Use the strtol() function to convert the input string to a long integer. The function takes three arguments: the input string, a pointer to a char pointer to store the end of the converted string, and the base of the input string (usually 10 for decimal numbers).
Step 5: Check for errors in the conversion process. The strtol() function returns 0 if the conversion fails, so you can use this to check for invalid input strings.
Step 6: Display the converted long integer using the printf() function.
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[10];
long int num;
char* endptr;
printf("Enter a number as string: ");
scanf("%s", str);
num = strtol(str, &endptr, 10);
if (*endptr != '\0')
{
printf("Invalid input string.\n");
return 1;
}
printf("The converted long integer is %ld\n", num);
return 0;
}
Output:
Enter a number as string: 456
The converted long integer is 456
Code Explanation:
- We first include the header file stdlib.h to use the strtol() function.
- We declare a string variable str to store the input string, a long integer variable num to store the converted long integer, and a char pointer variable endptr to store the end of the converted string.
- We then use the scanf() function to read the input string from the user.
- The input string, the address of the endptr variable, and the base (10 for decimal numbers) are passed as arguments to the strtol() function, which converts the input string to a long integer and assigns it to the num variable. The endptr variable points to the end of the converted string.
- We check for errors in the conversion process by checking if the endptr points to the end of the input string (‘\0’). If it doesn’t, this means that the input string is invalid, so we display an error message and return 1 to indicate an error.
- Finally, we display the converted long integer using the printf() function.
- This method is useful when you need to perform error handling or deal with input strings of different bases, but it requires more code than the atoi() function.
Approach-3: How to convert string to number in c Using the sscanf() Function
The sscanf() function in C can be used to read formatted data from a string. It can be used to convert a string to a number by presenting the format of the input string.
Algorithm:
Step 1: Declare a string variable and initialize it with the input string
Step 2: Declare a variable of the desired data type and initialize it to 0
Step 3: Use the sscanf() function to read the formatted data from the string and store it in the variable
Code:
#include <stdio.h>
int main() {
char str[10] = "1234";
int num = 0;
sscanf(str, "%d", &num);
printf("The converted number is: %d\n", num);
return 0;
}
Output:
The converted number is: 1234
Code Explanation:
- The code includes the standard input-output header file “stdio.h”.
- The main function is defined, which is the starting point of the program.
- A character array ‘str’ of size 10 is declared and initialized with the value “1234”.
- An integer variable ‘num’ is declared and initialized with the value 0.
- The function ‘sscanf’ is called, which converts a string ‘str’ into an integer value and stores it in the integer variable ‘num’. It uses the format specifier “%d” to indicate that the input string should be converted to an integer.
- The printf function is called to display the value of ‘num’.
- The return statement terminates the program and returns 0 to the calling process.
Approach-4: How to change string to number in c Using the strtol() Function with Base Parameter
The strtol() function can also be used with a base parameter to convert a string to a number of a specific base. This method is useful when you need to convert strings in different bases, such as hexadecimal or octal, to decimal numbers.
Algorithm:
Step 1: Declare a string variable and initialize it with the input string
Step 2: Declare a variable of the desired data type and initialize it to 0
Step 3: Use the strtol() function to convert the string to the desired number type with the specified base.
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[10] = "FF";
int num = 0;
num = strtol(str, NULL, 16);
printf("The converted number is: %d\n", num);
return 0;
}
Output:
The converted number is: 255
Code Explanation:
- The strtol() function converts a string to a long integer with a specified base.
- In the code above, the strtol() function reads the hexadecimal value from the str variable and stores it in the num variable.
- The 16 parameter specifies that the input string is in hexadecimal format.
- The NULL parameter is used to indicate that the function should not return a pointer to the first invalid character in the input string.
- The num variable is updated with the converted value of the input string.
- Finally, the value of the num variable is printed using printf().
Best Approach: Using the strtol() Function with Base Parameter
After comparing all four approaches for converting a string to a number in C, the strtol() function with the base parameter is the best approach. Here’s why:
- strtol() can handle errors and provide better error-checking than the other functions.
- strtol() can handle input strings of different bases, making it more versatile than the other functions.
- sscanf() can be used to convert a string to a specific type of number, but it is more complicated and less efficient than strtol().
- atoi() and strtol() without the base parameter are simpler, but they lack the versatility and error-handling of strtol().
Sample Problems On How To Change StringTo Number In C
Sample Problem-1:
Scenario:
You are working on a project where you need to read in a user input string and convert it to an integer. You want to use the atoi() function in C to accomplish this task.
Solution Steps:
- Read in the user input string using the fgets() function in C.
- Use the atoi() function to convert the string to an integer.
- Handle any errors that may occur during the conversion process.
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[10];
int num;
printf("Enter a number: ");
fgets(str, 10, stdin);
num = atoi(str);
printf("The integer value of the input is %d\n", num);
return 0;
}
Output:
Enter a number: 356
The integer value of the input is 356
Code Explanation:
- The char array str is declared to store the user input string.
- The int variable num is declared to store the converted integer value.
- The printf() function is used for the user to enter a number.
- The fgets() function is used to read in the user input string from the console.
- The atoi() function is used to convert the input string to an integer value and store it in the num variable.
- The printf() function is used to print the integer value of the input.
Sample Problem-2:
Scenario:
You are developing a program that needs to parse user input for an IP address in dotted decimal notation (e.g. 192.168.1.1) and convert it to a 32-bit unsigned integer. You need a reliable and efficient method to perform this conversion.
Solution Steps:
- Take the user input for the IP address as a string.
- Use the strtol() function to convert each segment of the IP address to a long integer.
- Combine the four segments into a single 32-bit unsigned integer using bitwise operations.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
int main() {
char ip_str[16];
uint32_t ip_int = 0;
int i = 0;
char *token = NULL;
char *delim = ".";
char *save_ptr = NULL;
printf("Enter an IP address in dotted decimal notation: ");
fgets(ip_str, 16, stdin);
ip_str[strcspn(ip_str, "\n")] = 0;
token = strtok_r(ip_str, delim, &save_ptr);
while (token != NULL) {
uint32_t segment = strtol(token, NULL, 10);
ip_int |= segment << (24 - (i * 8));
token = strtok_r(NULL, delim, &save_ptr);
i++;
}
printf("IP address in integer form: %u\n", ip_int);
return 0;
}
Output:
Enter an IP address in dotted decimal notation: 192.168.1.1
IP address in integer form: 3232235777
Code Explanation:
- The program first prompts the user to input an IP address in dotted decimal notation and stores it as a string in the ip_str variable.
- It then initializes the ip_int variable to zero and sets up variables for tokenizing the string using the strtok_r() function.
- The program uses a while loop to tokenize the IP address string using the strtok_r() function and convert each segment to a long integer using the strtol() function.
- The program then combines the four segments into a single 32-bit unsigned integer using bitwise operations.
- Finally, the program prints the integer form of the IP address using the printf() function.
Sample Problem-3:
Scenario:
You have a string containing a person’s name and their age in the format “John Doe, 25”. You need to extract the name and age from the string and store them as separate variables.
Solution Steps:
- Declare variables to store the name and age.
- Use the sscanf() function to extract the name and age from the string.
- The format string should specify the expected format of the input string, including any delimiters or spaces.
- The extracted values can be stored in the variables declared earlier.
Code:
#include <stdio.h>
int main() {
char input_string[] = "John Doe, 25";
char name[50];
int age;
sscanf(input_string, "%[^,], %d", name, &age);
printf("Name: %s\n", name);
printf("Age: %d\n", age);
return 0;
}
Output:
Name: John Doe
Age: 25
Code Explanation:
- The sscanf() function is used to extract the name and age from the input string.
- The format string “%[^,], %d” specifies that the function should look for a sequence of characters that are not commas (%[^,]) followed by a comma and a space, and then an integer (%d).
- The extracted name is stored in the name variable, and the extracted age is stored in the age variable.
- The printf() function is used to display the extracted values on the screen.
Sample Problem-4:
Scenario:
Suppose you are working on a project that requires you to convert hexadecimal strings to decimal numbers. You have a list of hexadecimal strings and you need to convert each string to a decimal number for further processing.
Solution Steps:
- Declare an array of hexadecimal strings.
- Use the strtol() function with a base parameter of 16 to convert each hexadecimal string to a decimal number.
- Store the decimal numbers in a new array.
- Print the decimal numbers.
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
char hexStrings[][10] = {"A", "1F", "3C", "5D", "7E"};
int decimalNumbers[5];
int i;
for (i = 0; i < 5; i++) {
decimalNumbers[i] = strtol(hexStrings[i], NULL, 16);
}
printf("Hexadecimal Strings: %s %s %s %s %s\n", hexStrings[0], hexStrings[1], hexStrings[2], hexStrings[3], hexStrings[4]);
printf("Decimal Numbers: %d %d %d %d %d\n", decimalNumbers[0], decimalNumbers[1], decimalNumbers[2], decimalNumbers[3], decimalNumbers[4]);
return 0;
}
Output:
Hexadecimal Strings: A 1F 3C 5D 7E
Decimal Numbers: 10 31 60 93 126
Code Explanation:
- The standard libraries stdio.h and stdlib.h are included.
- The main() function is defined and declared as an integer function.
- An array of 5 hexadecimal strings is created using the char data type and the two-dimensional array syntax.
- An integer array is created with space for 5 integers.
- A for loop iterates over the length of the hexStrings array.
- strtol() function is used to convert each hexadecimal string in hexStrings to an integer and store the result in the corresponding index of the decimalNumbers array.
- Finally, the printf() function is used to print both the hexStrings array and decimalNumbers array to the console.
Conclusion
In conclusion, we have explored different approaches to convert strings to numbers in C. The four approaches discussed were atoi() function, strtol() function, sscanf() function, and strtol() function with a base parameter. We provided sample problems and solutions to illustrate using these methods and discussed the pros and cons of each approach.
Based on our analysis, the strtol() function with a base parameter is the best approach when dealing with strings in different bases. However, the choice of the method will depend on the specific requirements of the problem at hand.