以下代码是我的任务调度程序的文件读取功能。一切都很好,直到它试图读取代表截止日期的数字序列(例如,1,2,3,4,5)。而不是整数,一些随机数被添加到表“截止日期”。有谁知道这个问题的解决方案?
#include <iostream>
#include <vector>
#include <cstdlib>
#include <fstream>
#include <map>
#include <time.h>
using namespace std;
class Task{
public:
string Name;
int Number;
int Operation_Time_Machine_One;
int Operation_Time_Machine_Two;
int Task_Deadline;
};
int Maximum_Time_Between_IDE;
int IDE_Duration;
int Read_File(){
string FileName= "";
cout << "Please enter file name (with .txt):\t";
cin >> FileName;
std::vector<Task> Task_Vector;
FILE* OpenedFile = fopen(FileName.c_str(),"r");
int Number_Of_Tasks=0;
int Duration_Of_Operation_One =0;
int Duration_Of_Operation_Two =0;
if( OpenedFile == NULL){
exit(EXIT_FAILURE);
}
else{
fscanf(OpenedFile,"%d", &Number_Of_Tasks);
for (int i=0; i<= Number_Of_Tasks;i++){
Duration_Of_Operation_One=0;
Duration_Of_Operation_Two=0;
fscanf(OpenedFile, "%d, %d", &Duration_Of_Operation_One, &Duration_Of_Operation_Two);
Task New_task;
New_task.Name ="task" ;
New_task.Number = (i+1);
New_task.Operation_Time_Machine_One = Duration_Of_Operation_One;
New_task.Operation_Time_Machine_Two = Duration_Of_Operation_Two;
New_task.Task_Deadline =0;
Task_Vector.push_back(New_task);
}
fscanf(OpenedFile,"%d", &Maximum_Time_Between_IDE);
fscanf(OpenedFile,"%d", &IDE_Duration);
int Deadlines[Number_Of_Tasks];
//from now it's gettig weird
for(int i=0; i<=Number_Of_Tasks;i++){
fscanf(OpenedFile,"%d, ", &Deadlines[i]);
}
for(int i=0; i<=Number_Of_Tasks;i++){
cout<<Deadlines[i]<<endl;
}
}
fclose(OpenedFile);
return 0;
}
int main()
{
clock_t time;
time = clock();
std::cout << "Hello world!" << std::endl;
Read_File();
time = clock() - time;
printf ("Time of algorithm %f seconds.\n",((float)time)/CLOCKS_PER_SEC);
return 0;
}
示例输入:
5
74, 64
27, 74
69, 47
35, 54
101, 86
102
6
113, 242, 344, 144, 513
答案 0 :(得分:2)
有一些错误..
int Deadlines[Number_Of_Tasks]
C ++中不允许使用VLA。因此,您应该删除C++
标记,或在您想要VLA的任何地方使用std::vector
。即std::vector<int> Deadlines(Number_Of_Tasks);
for(int i=0; i <= Number_Of_Tasks; i++)
.... Deadlines[i]
你超出了数组的范围,导致了未定义的行为。你想要做的是(在最后两个循环中):
for(int i=0; i < Number_Of_Tasks; i++)
^^^
最后,不要将C和C ++结合起来,它们是两种不同的编程语言。为您的程序选择其中一个并坚持下去。