Reputation: 1
The code below is file reading function for my task scheduling program. Everything is OK, until it tries to read sequence of numbers (ex 1, 2, 3, 4, 5) representing deadlines. Instead of ints some random numbers are added to the table "Deadlines". Does anyone know solution for this problem?
#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;
}
Sample input:
5
74, 64
27, 74
69, 47
35, 54
101, 86
102
6
113, 242, 344, 144, 513
Upvotes: 0
Views: 300
Reputation: 29352
There are some errors..
int Deadlines[Number_Of_Tasks]
VLA's are not allowed in C++. Therefore you should remove the C++
tag, or use std::vector
everywhere you want a VLA. i.e std::vector<int> Deadlines(Number_Of_Tasks);
for(int i=0; i <= Number_Of_Tasks; i++)
.... Deadlines[i]
you're exceeding the bounds of the array, which leads to undefined behavior. What you want to do is (in both the last two loops):
for(int i=0; i < Number_Of_Tasks; i++)
^^^
Finally, don't combine C and C++ which are two different programming languages. Choose one of them for your program and stick to it.
Upvotes: 3