Wednesday, January 6, 2010

itoa & atoi - C/C++

itoa & atoi - C/C++

itoa:
char * itoa ( int value, char * str, int base );
Convert integer to string (non-standard function)

Converts an integer value to a null-terminated string using the specified base and stores the result in the array given by str parameter.

If base is 10 and value is negative, the resulting string is preceded with a minus sign (-). With any other base, value is always considered unsigned.

Return Value:A pointer to the resulting null-terminated string, same as parameter str.

This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.

A standard-compliant alternative for some cases may be sprintf:
sprintf(str,"%d",value) converts to decimal base.
sprintf(str,"%x",value) converts to hexadecimal base.
sprintf(str,"%o",value) converts to octal base.


/* itoa example */
#include < stdio.h >
#include < stdlib.h >

int main ()
{
int i;
char buffer [33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,buffer,10);
printf ("decimal: %s\n",buffer);
itoa (i,buffer,16);
printf ("hexadecimal: %s\n",buffer);
itoa (i,buffer,2);
printf ("binary: %s\n",buffer);
return 0;
}

Output:
Enter a number: 1750
decimal: 1750
hexadecimal: 6d6
binary: 11011010110


atoi:

int atoi ( const char * str );
Convert string to integer

Parses the C string str interpreting its content as an integral number, which is returned as an int value.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

Return Value-On success, the function returns the converted integral number as an int value.
If no valid conversion could be performed, a zero value is returned.

/* atoi example */
#include < stdio.h >
#include < stdlib.h >

int main ()
{
int i;
char szInput [256];
printf ("Enter a number: ");
fgets ( szInput, 256, stdin );
i = atoi (szInput);
printf ("The value entered is %d. The double is %d.\n",i,i*2);
return 0;
}

Output:

Enter a number: 73
The value entered is 73. The double is 146.


Also, check out Free ISTQB Training Material here

www.testing4success.com - Application QA/Testing     Mobile App QA/Testing     Web Testing     Training
Iphone App QA  Android App QA  Web QA 

No comments:

Post a Comment