我正在尝试为一个类构建一个简单的计算器,但是由于某种原因,该程序一直崩溃。
我环顾四周,没有发现什么可以告诉我怎么了,所以我想在这里问。
现在的诀窍是,我们最多只能学习if/else语句,因此这是我们可以使用的唯一功能。

#include <stdio.h>

void main() {
  float num1, num2;
  int type;
  char oper;

  printf_s("Please enter your choise:\n1. Decimal calculator.\n2. Binary            calculator.\n");
  scanf_s("%d", &type);

  if (type == 1) {
    printf_s("Please enter the equation you want to solve and then press Enter:\n");
    scanf_s("%f %c %f",&num1,&oper,&num2);
  }
}


有人知道这是怎么回事吗?例如,每当我输入1 + 1时,程序就会崩溃。

谢谢!

最佳答案

您的问题是scanf_s需要buffer size specifier after every %c %s and %[。有关类似问题,请参见this post。实际上,scanf并没有这个问题,您实际上所做的是将num2地​​址的值作为%c的缓冲区大小指定符放在:

scanf_s("%f %c %f",&num1,&oper,&num2);


请注意,即使printf_s has additional requirements

在仍然使用scanf_s的情况下,这里的解决方法是:

#include <stdio.h>


int main() {
    float num1, num2;
    int type;
    char oper;
    const int oper_buff_size = 1;

    printf_s("Please enter your choise:\n1. Decimal calculator.\n2. Binary            calculator.\n");
    scanf_s("%d", &type);

    if (type == 1) {
        printf_s("Please enter the equation you want to solve and then press Enter:\n");
        // note oper_buff_size, the buffer size of the char pointer
        scanf_s("%f %c %f", &num1, &oper, oper_buff_size, &num2);
        // test to show this works
        printf_s("Entered: %f %c %f", num1, oper, num2);
    }
    return 0;
}


您可能会问为什么我们需要指定%c格式的长度,因为它应该只是char的大小(以字节为单位)。我相信这是因为需要将字符的指针放在格式中,所以您不知道所指向的是char *数组还是仅指向char的指针(在这种情况下)

我还要添加一个附录,尽管这不是您的程序失败的原因,请避免使用跨平台不兼容的怪癖,例如void main,因为这会使人们更难在代码中发现真正的问题。不要使用void main(),请使用int main(...) and return 0; instead。 Void main在标准C或C ++中无效,它是Microsoft Visual Studio语言实现的怪癖。

关于c - 制作一个简单的计算器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43121159/

10-17 02:42