gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:20:16 25 4
gpt4 key购买 nike

我编写此代码是为了允许用户玩“猜数字”游戏。一旦用户猜对了数字,它就会询问用户是否想再玩一次。此代码适用于两次播放,如果用户输入“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com