How to allow user to input alphabets with space for name( e.g. John Mike) but disallow user to input alphabets with digits value?
Read in the entire line of input into a string and then process the string.
Assess the string for legitimate characters and patterns.
Important to be generous in what is valid and consider various culture issues. Name validity testing is a sensitive issue. Easy to get negative feed attempting to discuss it. Also may be considered not constructive.
Use isalpha()
for first level check and then check for other valid characters insuring at least one alpha.
isalpha()
is locale sensitive and offers some level of internationalization.
#include <ctype.h>
#include <stdbool.h>
bool name_test1(const char *s) {
const char *between_char = "-'"; // Allow O'Doul, Flo-Jo. Adjust as needed
bool valid = false;
while (*s) {
if (isalpha((unsigned char ) *s)) {
valid = true;
} else if (*s == ' ' && valid) { // or isspace((unsigned char) *s) for any white-space
valid = false; // valid char must follow
} else if (strchr(between_char, *s) != NULL && valid) {
valid = false; // valid char must follow
} else {
return false;
}
s++;
}
return valid;
}
The && valid
in *s == ' ' && valid
insures a leading space is not valid.
Example:
void ntest(const char *s) {
printf("%d <%s>\n", name_test1(s), s);
}
int main(void) {
ntest("John Mike");
ntest("John34 Mike");
ntest("John Mike ");
ntest(" John Mike");
ntest("Flo-Jo");
ntest("O'Doul");
char name[100];
while (fgets(name, sizeof name, stdin)) {
name[strcspn(name, "\n")] = '\0'; // lop off potential trailing \n
if (name_test1(name)) puts("Acceptable name");
else puts("Unacceptable name");
}
}
1 <John Mike>
0 <John34 Mike>
0 <John Mike >
0 < John Mike>
1 <Flo-Jo>
1 <O'Doul>
...
Best to not use scanf("%[^\n]",&name);
it has problems: It reads almost a line, the '\n'
is not read. A line of only "\n"
is a problem. It has no protection against over running the buffer.