Prof's transcribed code has weaknesses
#include<stdio.h>
int main(){
int n;
while(scanf("%d",&n)==0 || n <2 || n >20){
while ( getchar () != ’\n’);
printf( "Wrong. Try again\n");
}
printf ( "%n\n",n);
return 0;
}
Infinity loop
When input is closed after a scanf("%d",&n) == 0
, getchar()
can eventual return EOF
before '\n'
and thus while ( getchar () != ’\n’);
never ends.
Smart quotes
’\n’
vs. '\n'
. Transcription problem or is that in the original? In any case, the posted code was certainly not compiled.
Invalid specifier
"%n"
does not print the int
value. It is undefined behavior as "%n"
matches an int *
.
//printf ( "%n\n",n);
printf ( "%d\n",n);
Requirement weakness
"Ask the user a number between 2 and 20" is a classic ambiguity. Depending on perspective are 2 and 20 acceptable or not? Better to provide more detail
"Ask the user a number, inclusively, between 2 and 20" or the like.
OP code has issues too.
#include <stdio.h>
int main()
{
int number = -1;
printf("Enter a number in range [2,20]\n");
scanf("%d", &number);
while (number < 2 || 20 < number)
{
while (getchar() != '\n')
{
}
printf("Try again\n");
scanf("%d", &number);
}
printf("Your number was: %d", number);
return 0;
}
Failure to check input return value
scanf("%d", &number);
may have failed due to non-numeric text input. Check the result.
// scanf("%d", &number);
if (scanf("%d", &number) == 1) Success();
else Fail();
Infinite loop
OP's code suffers same potential infinite loop on end-of-file
// while (getchar() != '\n') { }
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) { }
Also check scanf()
return value.
Functional difference
With non-numeric input, Prof's code tries again. OP's code, which does not evaluate the return value of scanf()
, technically leads to trouble on rare input error. On input error, the value of number
is indeterminate. See comment
The 2 locations to take user input is simply twice the amount of code that needs checking. Better to take input from 1 call. Production code would have a get_int()
to handle this. Something like getint()
but is there a benefit to his method?
OP's' code does have an informative prompt.
Else not much, both need work. Perhaps
// untested code
#include<stdio.h>
#define MIN_N 2
#define MAX_N 20
int main(void) {
int cnt;
int n;
printf("Enter a number in range [%d,%d]\n", MIN_N, MAX_N);
while((cnt = scanf("%d",&n)) == 0 || ((cnt == 1) && (n < MIN_N || n > MAX_N))) {
int ch;
while ((ch = getchar ()) != '\n' && ch != EOF) {
;
}
printf( "Wrong input. Try again\n");
}
if (cnt == 1) printf ( "%d\n",n);
return 0;
}
Better code would read a line into a string and process the input with strtol()
.