0

The program should read in 5 values from a file and place them in an array. In the file, the elements are separated by a comma. I don't have to account for an empty new line. For some reason, I'm getting free(): invalid size.

#include <iostream>
#include <fstream>
using namespace std;

const int ARRAY_SIZE= 10000;

int main()
{
    ifstream file;
    string fileName= " ";
    
    string licensePlates[ARRAY_SIZE]= {" "};
    string dates[ARRAY_SIZE]= {" "};
    string times[ARRAY_SIZE]= {" "};
    int weights[ARRAY_SIZE]= {0};
    int speeds[ARRAY_SIZE]= {0};
    
    int violations= 0;
    int temporaryInt= 0;
    string temporaryString= " ";
    int index= 0;
    string dateReported= " ";
    string reportFile1Name= " ";
    string reportFile2Name= " ";
    string reportFile3Name= " ";
    bool otherDay= false;
    
    //ask user to input file name
    do
    {
        cout<< "Open File:";
        cin>> fileName;
        file.open(fileName);
        if(file.is_open()== false)
        {
            cout<< " Could not open "<< fileName<< endl;
            cin.clear();
        }
    }
    while(file.is_open()== false);

    //puts information from file into seperate arrays
    while(file.eof()== false)
    {
        getline(file, temporaryString, ',');
        licensePlates[index]= temporaryString;
        getline(file, temporaryString, ',');
        dates[index]= temporaryString;
        getline(file, temporaryString, ',');
        times[index]= temporaryString;
        file>> temporaryInt;
        weights[index]= temporaryInt;
        file>> temporaryInt;
        speeds[index]= temporaryInt;
        index++;
    }
    file.close();
}

`

I tried making array size bigger but that just returned the same problem. I tried changing the getline statements but nothing worked.

  • You got the bad file state `file.fail()`. You check only `file.eof()`, and even check it improperly. – 273K Oct 30 '22 at 20:56
  • I suspect an infinite loop, causing an overflow in your arrays, because the while loop condition is incorrect. – john Oct 30 '22 at 20:56
  • Probably that bad state is caused by you not accounting properly for the comma between the weight and speed. – john Oct 30 '22 at 20:57
  • Who taught you to write `while(file.eof()== false)`? That is always wrong. – john Oct 30 '22 at 20:58
  • If `file>> temporaryInt;` sees input that is not a number - like a comma - the stream will enter a failed state that is not eof. – BoP Oct 30 '22 at 20:58
  • Also, [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – Yksisarvinen Oct 30 '22 at 20:58

0 Answers0