The C array, character and string program example (secure version)

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

To do: Read character and string from the standard input and print to standard output using array variables (secure version)

To show: To show the relationship among array, character and string in C programming (secure version)

 

 

#include <stdio.h>

 

int main(void)

{

/* normal and array variables */

char sex, name[11], name1[11];

 

/* secure version of the formatted i/o */

printf_s("Enter your sex (M or F): ");

scanf_s("%c", &sex, 1);

 

printf_s("Enter your first name (max 10 characters): ");

scanf_s("%s", &name, 11);

 

printf_s("Enter your last name (max 10 characters): ");

scanf_s("%s", &name1, 11);

 

/* test whether male or female */

if (sex == 'M')

/* array name without brackets is the pointer to the first array's element */

printf_s("\nHow are you, Mr. %s %s?\n", name, name1);

else

printf_s("\nHow are you, Ms/Mrs. %s %s?\n", name, name1);

 

return 0;

}

 

Output example:

 

Enter your sex (M or F): M

Enter your first name (max 10 characters): Mike

Enter your last name (max 10 characters): Tyson

How are you, Mr. Mike Tyson?

Press any key to continue . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index