这个程序将要求一个数值并且只接受正值。输入字母或符号将导致scanf()
失败,程序将清除输入缓冲区并重试。在本例中,输入字母“q”将退出程序。您可以根据自己的情况进行调整。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int i = 0;
float n = 0.0f;
do {
printf("enter numeric value or q to quit\n");
if ( scanf("%f",&n) != 1) {// scan one float
while ( ( i = getchar ( )) != '\n' && i != 'q') {
//clear buffer on scanf failure
//stop on newline
//quit if a q is found
}
if ( i != 'q') {
printf ( "problem with input, try again\n");
}
}
else {//scanf success
if ( n == fabs ( n)) {
printf("number was %f\n", n);
}
else {
printf("positive numbers only please\n");
}
}
} while ( i != 'q');
return 0;
}
这已将上述内容改编为一个函数。
#include <stdio.h>
float getfloat ( char *prompt, int *result);
int main ( int argc, char* argv[])
{
float width, height, area;
int ok = 0;
do {
printf("\n\tArea of a Rectangle.\n");
width = getfloat ( "Enter the width of the rectangle or q to quit\n", &ok);
if ( ok == -1) {
break;
}
height = getfloat ( "Enter the height of the rectangle or q to quit\n", &ok);
if ( ok == -1) {
break;
}
area = width * height;
printf(" Area is %.1f\n", area);
} while (1);
return 0;
}
float getfloat ( char *prompt, int *result)
{
int i = 0;
float n = 0.0f;
*result = 0;
do {
printf("%s", prompt);
if ( scanf("%f",&n) != 1) {// scan one float
while ( ( i = getchar ( )) != '\n' && i != 'q') {
//clear buffer on scanf failure
//stop on newline
//quit if a q is found
}
if ( i != 'q') {
printf ( "problem with input, try again\n");
}
else {
*result = -1;
n = 0.0f;
}
}
else {//scanf success
if ( n == fabs ( n)) {
*result = 1;
}
else {
printf("positive numbers only please\n");
}
}
} while ( *result == 0);
return n;
}