In the following program, it checks to see what the user enters is a number or not:
Code:
#include <stdio.h>
#include <stdlib.h>
void clear_input(void);
int get_an_int(void);
double get_a_double(void);
// ************************************************************************** //
int main()
{
int qty, counter = 0;
double price, total = 0;
do {
printf("Enter quantitiy (0 to stop): ");
qty = get_an_int();
if(qty != 0) {
printf("Enter unit price: ");
price = get_a_double();
total += qty * price;
counter += qty;
}
} while (qty != 0);
printf("The total is %.2lf\n", total);
if (counter != 0) {
printf(" for %d items at an average price of %.2lf\n", counter,
total/counter);
}
system("PAUSE");
return 0;
} /* End Main */
// ************************************************************************** //
/* Clears out any input data remaining unprocessed. This function simply //
* reads characters until it encounters the new-line that terminates the //
* input line. //
*/
void clear_input(void)
{
char junk;
//do {
//scanf("%c", &junk);
//} while(junk != '\n');
while (getchar() != '\n')
; /* loop body is intentionally empty! */
} /* End clear_input
// ************************************************************************** //
/* Gets an int value from the user and clears out the rest of the input line. //
* The value entered is returned. If no int data is entered, the user is //
* given an error message and a change to re-enter. //
*/
int get_an_int(void)
{
int n;
while(0 == scanf("%d", &n)) {
//while((0 == n) || ('\n' != n)) { /* Almost works, but thinks that everything is an error */
clear_input(); // throw away the bad data
printf(" Error! Please enter an integer: ");
}
clear_input(); // throw away any extra data entered
return n;
} /* End get_an_int */
// ************************************************************************** //
/* Just like get_an_int, only gets a double rather than an int. //
*/
double get_a_double(void)
{
double n;
while (0 == scanf("%1f", &n)) {
clear_input(); // throw away the bad data
printf(" Error! Please enter a number: ");
}
clear_input(); // throw away any extra data entered
return n;
} /* End get_a_double */
/******************************************************************************/
The problem is that when you run the program it it only checks what the first inputted value is. If you input "123" it is ok "asb" gives an error, "123abc" gives an error, but if you enter "abc123" it givens an error. I have already asked, and i'm not allowed to use isdigit. So can somebody help me with this? I'd really like to know what the solution is.
Thanks in advance;
S0n1C!