You can read a single character and store it as type char using the format specifier %c.
For a string of characters, you use either the specifier %s or the specifier %[].
The string is stored as a null-terminated string with '\0' as the last character.
With the %[] format specification, the string to be read must include only the characters that appear between the square brackets.
^ excludes the characters.
%[aeiou] will read a string that consists only of vowels.
The first character that isn't a vowel will signal the end of the string.
%[^aeiou] reads a string that contains any character that isn't a vowel.
The first vowel or whitespace character will signal the end of the string.
#define __STDC_WANT_LIB_EXT1__ 1 #include <stdio.h> #define MAX_TOWN 10/*from www. ja va2 s .c o m*/ int main(void) { char initial = ' '; char name[80] = { ' ' }; char age[4] = { '0' }; printf("Enter your first initial: "); scanf_s("%c", &initial, sizeof(initial)); printf("Enter your first name: "); scanf_s("%s", name, sizeof(name)); fflush(stdin); if (initial != name[0]) printf("%s,you got your initial wrong.\n", name); else printf("Hi, %s. Your initial is correct. Well done!\n", name); printf("Enter your full name and your age separated by a comma:\n"); scanf_s("%[^,] , %[0123456789]", name, sizeof(name), age, sizeof(age)); printf("\nYour name is %s and you are %s years old.\n", name, age); return 0; }
This program expects you to enter your first initial and then your first name.
It checks that the first letter of your name is the same as the initial you entered.