I am currently tidying up my code for Mario problem for pset1 and I got stuck on the part where the user should be prompted for the integer again if the input is empty. I've been looking on various forums for 4 hours already and I can't seem to find an answer. It's either too complicated for me to understand and I doubt that such complex syntax is required to finish pset1 successfully or it doesn't work for me.
So far I tried to use two constructs for rejecting unwanted input and both of them worked equally well for me (they seem to reject everything, except for the empty input).
Here are they:
1) I used this one first, because I forgot about GetInt() from cs50 library. I found it here: https://stackoverflow.com/a/14099507
#include <stdio.h>
int clean_stdin()
{
while (getchar() != '\n');
return 1;
}
int height;
int line = 0;
int spc = 1;
int hash = 0;
int spcounter = 1;
int hashcounter = 1;
char z;
int main(void)
{
// prompts user for integer between 0 and 23
do
{
printf("Height:");
}
while (((scanf("%d%c", &height, &z)!=2 || z !='\n')
&& clean_stdin()) || height < 0 || height > 23);
In this example I thought that the function clean_stdin() should take care of an empty input, but it doesn't.
2) Then, I found that many people asked similar question and they were advised to use the cs50 code GetInt() which, evidently, makes the problem of rejecting incorrect input much easier and the code tidier, yet it still doesn't handle the empty input. If I hit enter when the program runs, instead of prompting me for input again, a new line is created. Here is the code:
#include <stdio.h>
#include <cs50.h>
int clean_stdin()
{
while (getchar() != '\n');
return 1;
}
int height;
int line = 0;
int spc = 1;
int hash = 0;
int spcounter = 1;
int hashcounter = 1;
char z;
int main(void)
{
// prompts user for integer between 0 and 23
do
{
printf("Height:");
height = GetInt();
}
while (height < 0 || height > 23);
What should I add to any of these two codes, so they reject empty input too? I can post my full code if you would like to.
Thanks in advance!