发现一个C语言scanf输入的奇怪bug,这里为什么会这样?

  • 首先贴上源代码吧:
#include<iostream>
#include <cstdio>
#include <stdlib.h>
using namespace std;

class Good {
public:
	short int time;
	short int value;
	Good() {
		cin >> this->time >> this->value;    // 使用cin输入时正常
//		scanf("%d%d", &this->time, &this->value);    // 使用scanf输入时运行错误
		printf("测试点 1\n");
	}
};

int main() {
	int T, M;	// T表示总时间,M表示总数目
	scanf("%d%d", &T, &M);
	Good *goods = new Good[M];
    printf("测试点 2\n");
	
	int *dp = new int[T + 1];
	for(int i = 0; i <= T; i++) dp[i] = 0;
    printf("测试点 3\n");
	
	for(int i = 0; i < M; i++) {
		for(int j = T; j >= goods[i].time; j--) {
			if(dp[j] < dp[j - goods[i].time] + goods[i].value)
				dp[j] = dp[j - goods[i].time] + goods[i].value;
		}
	}
	printf("%d\n", dp[T]);
	
	return 0;
}
  • 然后是出现问题的测试数据:
300 10
95 89
75 59
23 19
73 43
50 100
22 72
6 44
57 16
89 7
98 64
  • 在这里我遇到了一个奇怪的问题,那就是在Good的构造函数中,我使用scanf进行数据输入时,就会出现程序崩溃(崩溃原因不唯一,有时候停止在测试点1,有时候则是测试点2或者测试点3),而用cin输入也是正常的,十分诡异:

 

改成scanf("%hd%hd")试试

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632