I want to write a program so to read two POSITIVE INTEGER as input and reject if the user inputs anything other than two positive integers.I tried to use the following code but it does not work.
EDIT 1: Removed the first scanf. EDIT 2: Added code to check for negative values.
The code which does not work:
#include <stdio.h>
#include <stdlib.h>
int main () {
unsigned int no1,no2,temp;
char check;
printf("Enter two positive integers.\n");
scanf("%i %i %c", &no1, &no2 ,&check);
if(scanf("%i %i %c", &no1, &no2,&check) != 3 || check != '\n'){
printf("Invalid input!!.\n");
exit(EXIT_FAILURE);
}
else if (no1 <= 0 || no2 <= 0) {
printf("Invalid input!!.\n");
exit(EXIT_FAILURE);
}
int copy1,copy2;
copy1 = no1;
copy2 = no2;
while(no2 != 0) {
temp = no1 % no2 ;
no1 = no2;
no2 = temp ;
}
printf("The H.C.F. of %i and %i is %i. \n",copy1,copy2,no1);
return 0;
}
The working code:
#include <stdio.h>
#include <stdlib.h>
int main () {
int no1,no2,temp;
printf("Enter two positive integers.\n");
int numArgs = scanf("%i%i", &no1, &no2 );
if( numArgs != 2|| no1 <= 0 || no2 <= 0 ){
printf("Invalid input!!.\n");
exit(EXIT_FAILURE);
}
int copy1,copy2;
copy1 = no1;
copy2 = no2;
while(no2 != 0) {
temp = no1 % no2 ;
no1 = no2;
no2 = temp ;
}
printf("The H.C.F. of %i and %i is %i. \n",copy1,copy2,no1);
return 0;
}
It goes on till I input 5 integers or 2 characters consecutively other than \n. It never computes the H.C.F. However it works if I remove the "if" block.
EDIT 3: Now i do not want to read the newline.
The second if block to check for negative values is also not working.