Reputation: 1
Beginner here. I'm trying to trap a user into entering a positive number. However the while loop doesn't seem to be working for when the user enters and incorrect number.
Output:
Please enter a positive integer: -3
I'm sorry, you must enter a positive integer greater than zero: why?
I'm sorry, you must enter a positive integer greater than zero: -42
I'm sorry, you must enter a positive integer greater than zero: 42
The positive integer was : 42
Press any key to continue....
Code:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
void clear_keyboard_buffer(void);
int main()
{
int k;
printf("Please enter a positive integer: ");
scanf("%d", &k);
if (k > 0)
{
clear_keyboard_buffer();
printf("The positive integer was: %d ", k);
}
while (k<=0)
{
printf("I'm sorry, you must enter a positive integer greater than zero: ");
scanf("%d", &k);
return 0;
}
}
void clear_keyboard_buffer(void)
{
char ch;
scanf("%c", &ch);
while (ch != '\n')
{
scanf("%c", &ch);
}
}
Upvotes: 0
Views: 1242
Reputation:
Ok, I think it's easiest to show you some code that does what you want, along with some comments about why you should do it that way:
#include <stdio.h>
int main(void) /* note the void here, it says "no parameters"! */
{
int k;
/* here we don't use printf() because there is no formatting to do */
fputs("Please enter a positive integer: ", stdout);
scanf(" %d", &k); /* note the space, it consumes any whitespace */
while (k < 1)
{
fputs("I'm sorry, you must enter a positive integer greater "
"than zero: ", stdout);
scanf(" %d", &k);
}
printf("You entered `%d'\n", k);
return 0;
}
Still you should check the return value of scanf()
for production quality code because there could be errors (e.g. the user entering something that isn't a number ...)
That being said, for really reliable user input, I'd suggest to abandon scanf()
altogether and just use e.g. fgets()
to read a line of input (whatsoever) and then parse yourself. strtol()
could come handy ...
Just to give you an idea what I'm talking about, here's a very simple but reliable solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int readInt(void)
{
char buf[1024];
int input;
char *endptr;
fgets(buf, 1024, stdin);
/* strip off "end of line" characters */
buf[strcspn(buf, "\r\n")] = 0;
input = strtol(buf, &endptr, 10);
/* sanity check, only accept inputs that can be wholly parsed as
* an integer
*/
if (buf[0] == 0 || *endptr != 0) input = -1;
return input;
}
int main(void)
{
int k;
fputs("Please enter a positive integer: ", stdout);
k = readInt();
while (k < 1)
{
fputs("I'm sorry, you must enter a positive integer greater "
"than zero: ", stdout);
k = readInt();
}
printf("You entered `%d'\n", k);
return 0;
}
Upvotes: 1