C Character Functions
There are several types of character functions in the standard C library. One type of character functions is character classification functions. They are isuppper, islower, isdigit, isspace, and other boolean functions. For example, if (isupper(ch)) determines whether ch is upper case or not.
Another type of character functions is character conversion functions. They are toupper, tolower, and others. For example, ch = toupper(ch) converts ch to upper case whether the original is lower case or upper case.
Here is the same code for the character functions:
/*
*
* ctype.c
*
* Program to show examples of the use of isupper, toupper, etc.
*
* by Mark Virtue, 2001.
*
*/
#include <stdio.h>
#include <ctype.h>
main() {
char ch;
printf("Please type in a character (enter q to quite): ");
scanf("%c", &ch);
while (ch != 'q') {
if (isupper(ch)) {
printf("This is an uppercase charactern");
ch = tolower(ch);
printf("Lowercase equivalent is '%c'n", ch);
}
else if (islower(ch))
printf("This is an lowercase charactern");
else if (isdigit(ch))
printf("This is an digitn");
else if (isspace(ch))
printf("This is an space-type charn");
else
printf("This is an unknown charn");
printf("Please type a character (enter q to quite): ");
while (getchar() != 'n' && getchar() != EOF) {}
scanf("%c", &ch);
}
fflush(stdin);
}
More C Strings Input and Output Functions
For the input function, the gets function is much more simpler to use than the scanf function. The scanf function is often used in the advanced C programs. The same is for the output function. the puts function is more simpler to use than the printf function. Here are the definitions for these functions:
- puts – Put String
- gets – Get String
- fgets – File Get String
As you can see in the above definitions, the fgets function is used to get the value from a file. However, fgets is also often used in place of the gets function because gets is mostly misused by programmers.
Here is the sample code for these functions:
/*
*
* string.c
*
* Program to illustrate the use of gets, puts and fgets
*
* by Mark Virtue, 2001.
*
*/
#include <stdio.h>
#include <string.h>
main() {
char name[21];
puts("This is a basic programn");
fputs("Please enter your full name (20 characters max): ", stdout);
fgets(name, 21, stdin);
fputs("Your full name is ", stdout);
puts(name);
fflush(stdin);
if (strlen(name) >= 20)
while (getchar() != 'n' && getchar() != EOF) {}
getchar();
}
Note that when I used GCC to compile the above code with gets function, the GCC compiler would give me a warning stated that the gets function is dangerous and should not use it. Therefore I recommend to use fgets to make things easier.
Also notice that the above code contains a new function, fputs. As my current knowledge, the difference between fputs and puts is that puts automatically adds a break (n) at the end of each output, whereas fputs does not. The fputs function is good to display the prompt for user to enter the data.