I've got a simple program which asks users for a number 1- 10 and then checks if its a digit or not. At the end I want to prompt the user if they want to continue or exit
and if they want to continue I want to go back to the top.
I put the user's data in an array called c[i] for each character using getchar() and a
loop.
I've read that to clear the input buffer I need to do something like:
while( (d = getchar()) && d != '\n' && d != EOF)
d = getchar;
Problem, input buffer doesn't get cleared. If it put another clear buffer at the top then the user must hit enter but they don't know that.
insert
Code:
int main()
{
int i, j;
char c[100];
int lengthOfInput = 0;
char d = 0;
j = 0;
while ( j == 0 )
{
// initialize array
for (i = 0; i <= 100; ++i)
{
c[i] = '\0';
}
/* Ask for input */
printf("Enter a number from 1-10.\n");
for (i = 0; c[i - 1] != '\n'; ++i) {
c[i] = getchar();
lengthOfInput += 1;
}
/* Take care of 10 */
if (((lengthOfInput-1) == 2) && (c[0] == '1') && (c[1] == '0'))
printf("\'10 divided by 25 is %.1f'\n", 10.0/25.0);
else if ((lengthOfInput-1) == 1)
{
if (isdigit(c[0]))
{
switch(c[0])
{
case '4':
printf("You chose %c. 4 + 10 is %d.\n", c[0], 4 + 10);
break;
default:
printf("You chose %c.\n", c[0]);
break;
}
}
else
{
printf("Not a valid digit\n");
}
}
else
printf("Not a valid digit 2.\n");
printf("Hit 0 to continue\n");
while ((d = getchar()) && d != '\n' && d != EOF) {
d = getchar();
if (d != '0')
j = 1;
}
}
}