c++ - 如何处理这个异常

标签 c++ c exception

我编写此代码是为了允许用户玩“猜数字”游戏。一旦用户猜对了数字,它就会询问用户是否想再玩一次。此代码适用于两次播放,如果用户输入“y”第三次再次播放,则代码显示异常。异常详细信息为:“Ex 5.32 猜数字.exe 中 0xFEFEFEFE 处未处理的异常:0xC00001A5:已检测到无效的异常处理程序例程(参数: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;}
}

最佳答案

让您的 scanf_s 使用正确的格式:

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

而不是:

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

如果您使用标准 scanf(),使用错误的格式字符串可能会导致未定义的行为……对于 scanf_s() 来说,情况不太乐观,但它可以'不乖。

另请注意 scanf_s()需要通过字符或字符串输入传递大小(因此 YesOrNo 参数后面有 1):

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.

另外...您用 C 和 C++ 标记了它,请注意,C 允许您从自身内部调用 main() while C++ does not 。不过,坦率地说,在我看来,从来没有充分的理由这样做,而且我也不认为您的程序有充分的理由这样做。

关于c++ - 如何处理这个异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22587091/

相关文章:

c++ - 分配给数组成员时 Clang 中的 "Read-only variable is not assignable"

c++ - Windows 7奇怪的异常现象

java - 使用 Hibernate 捕获 PSQLException

c++ - 如何在没有任何临时字符数组作为变量的情况下将字符数组传递给 C++ 中的函数?

c++ - 使用 OpenGL 分配的纹理内存受什么限制?

c++ - 将 1 到 32 位数字附加到 char 缓冲区

c - 在 C 中随机用 2​​ 个整数填充数组

c - 归并排序: Incorrect answer

C 计算字符串中 n 长度单词的出现次数

c++ - 对于 "-fno-exceptions", "new T"会发生什么?