The primary purpose of this program is to practice catching if the user enters data that does not correspond to expected input. Note if the user enters their name as "123", this is valid as it can be used as an identity, however if users enter only spaces (i.e. " ") or just a newline char then their input will be rejected. Also note preceding and trailing spaces are OK as long as there is some form of symbol present in the entire name.
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define BUFFSIZE 10
/*Checks to see if name contains actual characters and not just whitespace*/
bool isThereChars(const char * name)
{
bool charCheck = false;
for (size_t index = 0; index < BUFFSIZE; ++index) {
if (name[index] != ' ' && name[index] != '\0')
charCheck = true;
}
return charCheck;
}
void retreiveName(char* name)
{
for (;;) {
if (fgets(name, BUFFSIZE, stdin) != NULL) {
name[strcspn(name, "\n")] = '\0';
if (name[0] == '\0' || isThereChars(name) == false) {
printf("Invalid name entered please try again...\n");
}
else
return;
}
else
printf("Memory could not be allocated please try again...\n");
}
}
int main(void)
{
char name[BUFFSIZE];
printf("Enter Name: ");
retreiveName(name);
printf("Your name is: %s\n", name);
printf("Press enter to continue...\n");
getchar();
return 0;
}