0

I was trying to build the game of rock paper scissors in C. When I made it for playing one single time, it was working properly. But when I tried to make it run for multiple number of times using for loop, it failed to scan the value given by the user. It is running the code correctly when it is the eventh turn, i.e , 2nd,4th,6th and so on. But it fails to take the input when it is odd turn. The code is given below:

#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>

int main()
{
   int n;
   printf("Enter the number of times you want to play rock paper scissors: ");
   scanf("%d", &n);
   
   for(int i=0;i<n;i++){
    char c,p;
    
    //creating random rps generator
    int num;
    srand(time(0));
    num=rand()%3+1;

    
    if(num==1){
        c='r';
    }
    else if(num==2){
        c='p';
    }
    else{
        c='s';
    }
    
    //Taking input from the user
    printf("Enter rock(r),paper(p) or scissors(s) : ");
    scanf("%c",&p);
    
    
    //Main code
    if(c==p){
        printf("It's a draw.\n");
    }
    else if((c =='r' && p =='p') || (c =='p' && p =='s') || (c =='s' && p =='r')){
        printf("You win.\n");
    }
    else if((c =='p' && p =='r') || (c =='s' && p =='p') || (c =='r' && p =='s')){
        printf("You lose.\n");
    }
   }
    return 0;
}
  • 1
    Beginners tend to put the blame on the tools before questioning what they did. [Socrates] –  Feb 17 '22 at 07:53
  • 3
    Answered [here](https://stackoverflow.com/questions/5240789/scanf-leaves-the-newline-character-in-the-buffer) or [here](https://stackoverflow.com/a/13543113/2115408) – mmixLinus Feb 17 '22 at 07:57
  • Yes, when you don't use it properly, it will not work properly. Proper use includes checking the return value — every single time. If you don't check, it logically follows that you don't care whether it worked. – n. m. could be an AI Feb 17 '22 at 08:00
  • 1
    Unrelated, but whoever taught you to call `srand` in a loop knows not what they are talking about. Call `srand` once before the loop. – n. m. could be an AI Feb 17 '22 at 08:03
  • It works as it is designed to work, but it's possible you aren't familiar with the quirks, or disagree with its spec. – Weather Vane Feb 17 '22 at 08:41
  • Please be consistent in your indentation. At the beginning, I see 3 space indentation and I nearly missed the for loop because it was incremented by only 1 space. Also, some if later are indented by 4 space. The code end up harder to read. – Tom's Feb 17 '22 at 09:10

0 Answers0