-1

I am writing this code to allow user to play game "Guess the number". Once the user guesses right number it asks user if he/she wants to play again. This code works for two plays and if user inputs 'y' to play again for third time, the code shows exception. The exception details are:"Unhandled exception at 0xFEFEFEFE in Ex 5.32 Guess the number.exe: 0xC00001A5: An invalid exception handler routine has been detected (parameters: 0x00000003)."

 #include "stdafx.h"
 #include <math.h>
 #include <stdlib.h>
int a = 1;

int main(int g){
int num, guess;
char YesOrNo;
srand(g);
num = 1 + rand() % 1000;
printf("I have a number between 1 and 1000\nCan you gess my number?\n");

do{
    scanf_s("%d", &guess);
    if (guess == num){
        printf("Excellent! You guessed the number!\n");
        break;
    }
    else if (guess < num)
        printf("Too low. Try Again.\n");
    else
        printf("Too High. Try Again.\n");
} while (1);
printf("Would you like to play again(y or n) ? ");
scanf_s("%s", &YesOrNo);
if (YesOrNo == 'Y' || 'y'){
    a++;
main(a);
  }
    else{
   return 0;}
}
user3451261
  • 676
  • 1
  • 7
  • 4
  • 1
    Why did you use `int main(int g)`? That's not the standard way. And specify which language you are using, C or C++, they may have totally different solution for this problem. – Yu Hao Mar 23 '14 at 04:33
  • Choose a language: C or C++? – aschepler Mar 23 '14 at 04:36
  • `if (YesOrNo == 'Y' || 'y')` was probably meant to be `if (YesOrNo == 'Y' || YesOrNo == 'y' )`. Make sure you understand the difference between those two expressions. – M.M Mar 23 '14 at 05:59
  • Do summat about the indentation – Ed Heal Mar 23 '14 at 14:14

1 Answers1

1

Have your scanf_s use the correct format specificer:

scanf_s(" %c", &YesOrNo, 1);   // expecting a char

instead of:

scanf_s("%s", &YesOrNo);  // expecting a string

If you were using the standard scanf() using the wrong format string can lead to undefined behavior… not positive about the same for scanf_s() but it can’t be good.

Also note that scanf_s() requires a size to be passed with character or string input (hence the 1 after the YesOrNo parameter):

Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.

Also... you tagged this with both C and C++, note that C allows you to call main() from within itself while C++ does not. Although, frankly IMO there's never a good reason to do this, and I don't see a good reason for your program to.

Community
  • 1
  • 1
Mike
  • 47,263
  • 29
  • 113
  • 177