可能是另一个愚蠢的错误,但我真的无法理解这个问题。 我正在编写一个基本多项式类,我的程序在输入几个整数时突然崩溃。我尝试寻找解决方案,但找不到:/
代码:
#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", °ree);
//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”之前就退出,并且要输入我使用输入数字+回车键。
非常感谢您的帮助!
最佳答案
您的代码似乎工作正常。 为了编译它,我所做的唯一更改是注释掉使用 malloc 的行,并将打印语句放在一行上。
如果您使用的是较新版本的 Visual Studio,那么在使用 scanf 函数时会出现问题。您必须使用 scanf_s 或通过顶部的这一行禁用警告:
#pragma warning(disable: 4996)
希望这有帮助。
关于int 输入后,C 程序在使用 Scanf 时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50119645/