在 Dev C++ 中编译 & 运行 时程序崩溃

Program Crashes When I Compile & Run in Dev C++

#include <stdio.h>
#include <conio.h>
#include <string.h>

main()
{
float gross=0,otp=0,ot=0,pay=0;
int IC,hours=0;
char name[50];
char category;
char rep = 'y';


while(rep == 'y')
{

printf("\n\n Name : ");
gets(name);
printf("\n NRIC : ");
scanf ("%d",&IC);
printf("\n Category  : ");
scanf ("%s",&category);
printf("\n Total Hours  : ");
scanf("%d",&hours);

if (category = 'A1')  //Line 25
{
 if (hours < 44)
 {
    printf("\n INVALID INPUT\n");
 }
 else if (hours >= 44 && hours <= 60) 
 {
    gross= 44*5;
    ot= (hours-44)*(1/2*5);
    pay=gross+ot;
     printf("\n          Syarikat Smart Store Hypermarket Sdn. Bhd. ");
     printf("\n  =============================================================="); //Line 39
     printf("\n Name: %s", name);
     printf("\n NRIC: %d", IC);
     printf("\n Category: %s", category);
     printf("\n Total Hours: %d", hours);
     printf("\n Gross Pay: RM %.2f", gross);
     printf("\n Overtime Pay: RM %.2f", ot);
     printf("\n Net Pay: RM %.2f", pay);
 }
 else 
  {
     printf("\n\n INPUT NOT VALID");

我在代码中没有看到任何错误,除了第 25 行指出多字符字符常量警告,但程序运行到第 39 行并崩溃。知道为什么或我的代码中有任何错误会导致这种情况吗?

至少有两个问题,编译器已经指出了其中一个问题: 'A1' 不是您要用单引号 (') 括起来的单个字符。你需要双引号。

此外,可能更重要的是: 您实际上并没有在第 25 行执行比较,您正在 更改 category 的值( = vs == )所以这意味着如果您的输入与 A1 无关,因此其他事情可能是错误的或不适合输入这个特定的 if

编辑:如果你确实在使用 C,那么你应该使用差异函数来比较你的字符串,如 this page pointed to in this thread

中所示

所以你至少需要添加

#include <string.h>

然后将您的 if 更改为

  if ( strncmp(category,"A1",2) == 0 )  //Line 25  

我假设您将 category 变量的定义更改为例如char[50]name 一样,并且您的类别始终只有两个字母。

我的编译器还警告

warning: ‘char* gets(char*)’ is deprecated

所以你可能也应该考虑远离它。