HowToProgramC : Lesson 28


Back Home Next



String Conversion Functions

The header file stdlib.h includes functions, used for different conversions.

When we get input of a different type other than the type of variable in which the value is being stored, it warrants the need to convert that type into another type.

These conversion functions take an argument of a type and return it after converting into another type. These functions and their description are given in the table below.

Prototype Description
double atof( const char *nPtr ) Converts the string nPtr to double.
Int atoi( const char *nPtr ) Converts the string nPtr to int.
long atol( const char *nPtr ) Converts the string nPtr to long int.
double strtod( const char *nPtr, char **endPtr ) Converts the string nPtr to double.
long strtol( const char *nPtr, char **endPtr, int base )
Converts the string nPtr to long.
unsigned long strtoul( const char *nPtr, char **endPtr, int base )
Converts the string nPtr to unsigned long.

Use of String Conversion functions:

While writing main () in a program, we can put them inside the parentheses of main. ‘int arg c, char ** arg v are written inside the parentheses. The arg c is the count of number of arguments passed to the program including the name of the program itself while arg v is a vector of strings or an array of strings. It is used while giving command line arguments to the program.

The arguments in the command line will always be character strings. The number in the command line (for example 12.8 or 45) are stored as strings. While using the numbers in the program, we need these conversion functions.

Following is a simple program which demonstrate the use of atoi function. This program prompts the user to enter an integer between 10-100, and checks if a valid integer is entered.

//This program demonstrate the use of atoi function

# include <iostream.h>
# include <stdlib.h>

main( )
{

int anInteger;
char myInt [20]
cout << "Enter an integer between 10-100 : ";
cin >> myInt;

if (atoi(myInt) == 0)
cout << "\nError : Not a valid input"; // could be non numeric
else
{
anInteger = atoi(myInt);
if (anInteger < 10 || anInteger > 100)
cout << "\nError : only integers between 10-100 are allowed!";
else
cout << "\n OK, you have entered " << anInteger;
}
}

The output of the program is as follows.

Enter an integer between 10-100 : 45.5
OK, you have entered 45



Back Home Next


Google




learntoknow@yahoo.com
© All rights Reserved.