I am writing a program for an assignment which accepts a int number input for an age then prints out a relative message using if else statements. My problem is that it also converts an input when a letter is entered, Is there a way to stop this?
I am writing a program for an assignment which accepts a int number input for an age then prints out a relative message using if else statements. My problem is that it also converts an input when a letter is entered, Is there a way to stop this?
You can read the input into a char[] and then convert it to a number using atoi. if a non-number is entered then you would display an error message.
Ivan
Thanks for the info but I dont have enough knowledge to apply what you suggested, can you post an example?
Here is my code so where does the new part fit in?
# include <stdio.h>
# include <conio.h>
void main(void)
{
int age;
char answer;
clrscr();
do
{
{
printf("Please enter your age for a honest comment!\n");
scanf("%d", &age);
fflush(stdin);
clrscr();
if (age <= 0)
printf("\nSorry thats not possible:-(\n");
else if (age == 1 || age <= 29)
printf("\nIf you are %d years old then you are a youngster.\n", age);
else if (age <= 64)
printf("\nIf you are %d years old then welcome to mid life.\n", age);
else if (age <= 99)
printf("\nIf you are %d years old then you should be retired.\n", age);
else if (age >= 100)
printf("\nIf you are %d years old or over, are you still alive?\n", age);
else
printf("Please enter a number\n");
}
printf("\n\nDo you want to exit the program?(y/n)\n");
scanf("%c", &answer);
fflush(stdin);
clrscr();
}
while(answer == 'n' || answer == 'N');
printf("\nThis program was brought to you by ZeD\n");
scanf("%c");
fflush(stdin);
}
# include <stdio.h>
# include <conio.h>
void main(void)
{
char agetext[500];
int age;
char answer;
clrscr();
do
{
{
while (1)
{
printf("Please enter your age for a honest comment!\n");
scanf("%s", agetext);
// convert text to number
age = atoi(agetext);
// agetext not a number
if ( age == 0 )
printf("You did not enter a number");
else
break;
}
clrscr();
if (age <= 0)
printf("\nSorry thats not possible:-(\n");
else if (age == 1 || age <= 29)
printf("\nIf you are %d years old then you are a youngster.\n", age);
else if (age <= 64)
printf("\nIf you are %d years old then welcome to mid life.\n", age);
else if (age <= 99)
printf("\nIf you are %d years old then you should be retired.\n", age);
else if (age >= 100)
printf("\nIf you are %d years old or over, are you still alive?\n", age);
else
printf("Please enter a number\n");
}
printf("\n\nDo you want to exit the program?(y/n)\n");
scanf("%c", &answer);
fflush(stdin);
clrscr();
}
while(answer == 'n' || answer == 'N');
printf("\nThis program was brought to you by ZeD\n");
scanf("%c");
fflush(stdin);
}
Ivan