int 输入后,C 程序在使用 Scanf 时崩溃

标签 c scanf

可能是另一个愚蠢的错误,但我真的无法理解这个问题。 我正在编写一个基本多项式类,我的程序在输入几个整数时突然崩溃。我尝试寻找解决方案,但找不到:/

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Homework.h"
#include "Fraction.h"

int main()
{
  //Input from user
  int degree, i;
  printf("Insert the degree of the polynomomial: \n");
  scanf("%d", &degree);

  //Get the coefficcients
  struct fraction *bucket = malloc((sizeof(struct fraction))*(degree + 1));
  int num;
  unsigned int den;
  for(i = 0; i < degree + 1; i++)
  {
    num = 0;
    den = 1;
    printf("Insert the coefficcient of degree %d, first num and afterwards 
the den \n", i);
    printf("Numerator:\n");
    if(scanf("%d", &num) != 1)
      printf("Input error\n");
    printf("Denominator:\n");
    if(scanf("%u", &den) != 1)
      printf("Input error\n");
    //struct fraction temp = {num, den};
    //memcpy(&bucket[0], &temp, sizeof(struct fraction));
  }

  //Check insertion
  printf("Test\n");
  //print_fraction(bucket[0]);
}

程序甚至在打印“Test”之前就退出,并且要输入我使用输入数字+回车键。

非常感谢您的帮助!

最佳答案

Proof it compiles

您的代码似乎工作正常。 为了编译它,我所做的唯一更改是注释掉使用 malloc 的行,并将打印语句放在一行上。

如果您使用的是较新版本的 Visual Studio,那么在使用 scanf 函数时会出现问题。您必须使用 scanf_s 或通过顶部的这一行禁用警告:

#pragma warning(disable: 4996)

希望这有帮助。

关于int 输入后,C 程序在使用 Scanf 时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50119645/

相关文章:

c - 如何让 C 程序接受一次选项

c - 使用 fscanf() 跳转到下一行

c - C语言有哪些比较耗时的操作?

对 fork 函数感到困惑

c - 你如何在函数内部使用 struct 的 malloc?

c - 数组的 Scanf_s 错误

c - 如何在C中扫描用户定义的字符串数?

c - fscanf 格式说明符 - 以或不带注释字符串结尾的按列数字数据

c - 不知道如何修复错误

c - 我如何知道两个exe是否有不同的代码?