samedi 28 janvier 2017

Fscanf is not reading expected values from last line of file (C/C++)

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

Aucun commentaire:

Enregistrer un commentaire