Search code examples
c++arraysifstream

C++ Creating a variable sized array from ifstream


Just a heads up: My c++ programming skills and terminology is intermediate at best. So please be gentle ;).

I am working on a multi-sort algorithm for a college class. Originally, I built the program to take in an array of 20 integers, since that was as big as the .txt files were. The final lab is now asking to take in files that have 10, 100, 1000, 10000, 100000 and 1000000 different numbers. I originally used an ifstream inside a for loop to read in the ints. Now that I need to read a variable amount of ints from a file, I have run into issues with this code. I have extensively searched this site and Google to find an answer to this problem. I have tried dozens of different code snippets, to no avail. Here is the code I am currently running that works for 20 ints.

int i;
int A[20];
int length;
char unsortedFilename[200];
ifstream unsorted;

cout << "Please type the full name of the file you would like sorted.\n* ";
cin >> unsortedFilename;
unsorted.open(unsortedFilename);

length = (sizeof(A) / sizeof(*A));

for( i = 0; i < length; i++ )
{
    unsorted >> A[i];
    cout << A[i] << "\n";
}

insertionSort();

I do have other code mixed in there, but it's error checking, selection of duplicate number removal, etc. I would like it so that code like this would run "i" number of times, where "i" is actually the number of ints in the file. Also, as I mentioned earlier, I will need to input a file that has 1,000,000 numbers in it. I don't believe that an int array will be able to hold that many numbers. Is it going to be as easy as swapping all my ints over to longs?

Thanks for any help you could provide.


Solution

  • What you want is a vector.

    try this,

    int i;
    vector<int> A;
    int length;
    string unsortedFilename;
    ifstream unsorted;
    
    cout << "Please type the full name of the file you would like sorted.\n* ";
    cin >> unsortedFilename;
    unsorted.open(unsortedFilename);
    
    int temp;
    for( i = 0; unsorted >> temp; i++ )
    {
        A.push_back(temp);
        cout << A[i] << "\n";
    }
    
    insertionSort();
    

    A vector is basically a dynamic array. It automatically grows as more space is needed. That way it doesn't matter if you have 10, 100, or even 100000 items, it'll automatically grow for you.

    Also use a string for your file name, some file names are longer than 200 characters.

    Good Luck!