C 获取一个错误,声明;运行时检查失败#2-围绕变量';拒绝';他被腐蚀了。(Visual Studio)

C 获取一个错误,声明;运行时检查失败#2-围绕变量';拒绝';他被腐蚀了。(Visual Studio),c,C,我所有的代码都工作得很好,直到我按下键退出我的程序,这是在我按下“-”时发生的。然后我得到了那个错误,我不知道如何解决它。这是我的密码: #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <ctype.h> int main() { char rejected[2] = { 0 }; char input = 0; char exitProgram = 0; printf("Please ente

我所有的代码都工作得很好,直到我按下键退出我的程序,这是在我按下“-”时发生的。然后我得到了那个错误,我不知道如何解决它。这是我的密码:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>

int main() {

char rejected[2] = { 0 };
char input = 0;
char exitProgram = 0;

printf("Please enter three letters you want filtered\n");
for (int x = 0; x <= 2; x++) {
     scanf("%s", &rejected[x]);
}
printf("Please enter a letter and I will tell you if it is filtered or not\n");
for (int y = 0; y <= 99; y++) {
    scanf("%s", &input);
    if (input == rejected[0] || input == rejected[1] || input == rejected[2]) {
        printf("Filtered letter!\n");
    }
    else {
        printf("Okay letter!\n");
    }
    if (y %5 == 0) {
        printf("If you would like to exit this program, please enter '-'. If not, please enter '+'\n");
        scanf("%s", &exitProgram);
        if (exitProgram == '+') {
            printf("Okay, continue having fun with my program!\n");
        }
        else if (exitProgram == '-') {
            printf("Thank you for playing with my program!\n");
            break;
        }
    }
}
return 0;
}
\define\u CRT\u SECURE\u NO\u警告
#包括
#包括
int main(){
被拒绝的字符[2]={0};
字符输入=0;
char exitProgram=0;
printf(“请输入三个要过滤的字母\n”);

对于(int x=0;x您在三个位置使用了
scanf
,其中
%s
格式说明符用于读取字符串,而在这些位置中的每个位置都是不正确的。使用错误的格式说明符调用,这可能会导致崩溃

第一:

scanf("%s", &rejected[x]);
在这里,您确实需要读取单个字符,因此需要
%c
格式说明符。此说明符接受任何字符,包括空格和换行符,因此您需要在其前面加一个空格,以使用之前读取的任何剩余换行符:

scanf(" %c", &rejected[x]);
第二:

scanf("%s", &input);
input
是一个
char
,因此您再次希望
%c
在这里:

scanf(" %c", &input);
第三:

scanf("%s", &exitProgram);
您正在此处读取一个字符,因此请像以前一样使用带前导空格的
%c

scanf(" %c", &exitProgram);
您在这里也遇到了一个问题:

char rejected[2] = { 0 };
...
for (int x = 0; x <= 2; x++) {
     scanf("%s", &rejected[x]);
}

您在三个位置使用了
scanf
,使用了
%s
格式说明符,该说明符用于读取字符串,但在每个位置都不正确。使用错误的格式说明符调用会导致崩溃

第一:

scanf("%s", &rejected[x]);
在这里,您确实需要读取单个字符,因此需要
%c
格式说明符。此说明符接受任何字符,包括空格和换行符,因此您需要在其前面加一个空格,以使用之前读取的任何剩余换行符:

scanf(" %c", &rejected[x]);
第二:

scanf("%s", &input);
input
是一个
char
,因此您再次希望
%c
在这里:

scanf(" %c", &input);
第三:

scanf("%s", &exitProgram);
您正在此处读取一个字符,因此请像以前一样使用带前导空格的
%c

scanf(" %c", &exitProgram);
您在这里也遇到了一个问题:

char rejected[2] = { 0 };
...
for (int x = 0; x <= 2; x++) {
     scanf("%s", &rejected[x]);
}

rejected
声明为2个元素的数组,您将3读入其中,导致UB。
rejected
声明为2个元素的数组,您将3读入其中,导致UB。非常感谢,错误已经停止。但是,我注意到您说过输入应该是%d而不是%c,我不理解。对于输入,我是输入一个要读取的字符(如“c”或“p”)。%d不只是数字吗?非常感谢,错误已经停止。但是,我注意到您说输入应该是%d而不是%c,我不明白。对于输入,我输入一个要读取的字符(如“c”或“p”)。%d不只是数字吗?