Hello! I am a beginner in C programming. I was trying to write a program which asks a user to guess a secret number which is created by rand() function.
At this stage the program should tell how many digits of the nuber given by user coincide with digits of the secret number.
The problem is that even if the user guesses n digits, the program gives a number <n.
Example:
Enter a new number:3546
6305
number of guessed digits is 2
(In the middle is the secret number.)
Code:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
setvbuf(stdout,NULL,_IONBF,0);
int n=10000;
srand(time(NULL));
int r=rand()%n;
int d1,d2,d3,d4;
d1=r/1000;
d2=(r-d1*1000)/100;
d3=(r-d1*1000-d2*100)/10;
d4=r-d1*1000-d2*100-d3*10;
printf("%d,%d,%d,%d\n",d1,d2,d3,d4);
char c;
if(d1!=d2&&d1!=d3&&d1!=d4&&d2!=d3&&d2!=d4&&d3!=d4){
printf("Enter a number:");
scanf("%c",&c);
while(c!='\n'){
int k=0;
do{
c=getchar();
int digit=c-48;
if(digit==d1){
++k;
}
else if(digit==d2){
++k;
}
else if(digit==d3){
++k;
}
else if(digit==d4){
++k;
}
}while(c!='\n');
printf("%i\n",r);
printf("number of guessed digits is %i\n\n",k);
printf("Enter a new number:");
scanf("%c",&c);
}
}
return 0;
}
Thanks for help in advance!