3.2 Character-Conversion Functions

The character-conversion functions convert one type of character to another type. These functions include:

ecvt          _tolower
fcvt          toupper
gcvt          _toupper
mbtowc        towctrans
mbrtowc       wctrans
mbsrtowcs     wcrtomb
toascii       wcsrtombs
tolower

For more information on each of these functions, see the Reference Section.

Example 3-2 shows how to use the ecvt function.

Example 3-2 Converting Double Values to an ASCII String

/*  This program uses the ecvt function to convert a double    *
 *  value to a string. The program then prints the string.     */

#include <stdio.h>
#include <stdlib.h>
#include <unixlib.h>
#include <string.h>

main()

{

   double val;                     /*  Value to be converted   */

                                   /*  Variables for sign and  *
                                    *   decimal place          */
   int sign, point;

                                   /*  Array for converted     *
                                    *   string                 */
   static char string[20];

   val = -3.1297830e-10;

   printf("original value: %e\n", val);
   strcpy(string,ecvt(val, 5, &point, &sign));
   printf("converted string: %s\n", string);
   if (sign)
      printf("value is negative\n");
   else printf("value is positive\n");
   printf("decimal point at %d\n", point);
}

The output from Example 3-2 is as follows:

$ RUN  EXAMPLE2
original value: -3.129783e-10
converted string: 31298
value is negative
decimal point at -9
$

Example 3-3 shows how to use the toupper and tolower functions.

Example 3-3 Changing Characters to and from Uppercase Letters

/*  This program uses the functions toupper and tolower to     *
 *  convert uppercase to lowercase and lowercase to uppercase  *
 *  using input from the standard input (stdin).               */

#include <ctype.h>
#include <stdio.h>      /*  To use EOF identifier   */
#include <stdlib.h>

main()
{
   char c, ch;

   while ((c = getchar()) != EOF)
      {
         if (c >= 'A' && c <= 'Z')
            ch = tolower(c);
         else
            ch = toupper(c);
         putchar(ch);
      }
}

Sample input and output from Example 3-3 are as follows:

$ RUN  EXAMPLE3
LET'S GO TO THE stonewall INN.<Ctrl/Z>
let's go to the STONEWALL inn.
$


Previous Page | Next Page | Table of Contents | Index