I've done lots of programming and arduino and would like to learn in C, since this is also an requirement for my current study. At this moment, I am trying to make a program which checks if the "age" variable contains a character. This will give the user an error message which loops until the input is a number. This is what I have at the moment:
#include <stdio.h>
#include <ctype.h>
#define MAXIMUM 10
#define BASE 10
char name[MAXIMUM]; // Input[Range to prevent overflow]
int age = 0; // Input
int nage; // nage = age + 1;
int error1 = 0;
void errorProgram()
{
if (isdigit(age))
{
error1 = 0;
printf("Error = 0\n");
}
else {
error1 = 1;
printf("Error = 1\n");
}
}
void main(void)
{
system("cls");
printf("What is your name: ");
scanf("%15[^\n]", name);
system("cls");
printf("What is your age: ");
scanf("%d", &age);
errorProgram();
while (error1 != 0) {
printf("Age contains character, please enter again: ");
scanf("%d", &age);
}
nage = age + 1;
system("cls");
printf("Hello %s, you'll be %d next year.", name, nage);
return(0);
}
This is what happens when I run the program when we just ignore the what's your name part
Scenario 1(number)
Output
What is your age:
Input
5
Output
Error = 1
Age contains character, please enter again:
After I hit enter, it uses the while loop to ask it again until I have it right which is a wished behavior. However, it seems to detect age as a character?
Scenario 2(Character)
Output
What is your age:
Input
d
Output
Age contains character, please enter again: d
Age contains character, please enter again: Age contains character, please enter again: Age contains character, please enter again: Age contains character, please enter again: Age contains character, please enter again: Age contains character, please enter again: Age contains character, please enter again: Age contains character, please enter again: Age contains character,
I'd like to know why if I enter a character, it spams the console with the lines. Both 5 and d throws an error1 = 1, but the while function doesn't seem to behave the same way it does things different when it comes to the character.
Can someone explain this behavior?
Btw, I am using a template from my study which uses the "Void main". Hence it's a bit different.