Hello all, just hoping for a bit of understanding of new[]. I'm writing an insertion sort program for school (of course) and I've got most of it done; I have the program asking for a filename, and asking for file "size" (or how many numbers are in the file), and it successfully sorts. The problem I'm having is that I can't seem to figure out how to create a dynamic array for the file "size" when i don't know how big i need it to be. Once created, the size of the array won't change, so i won't need to worry about re-initializing or changing the array any.
//Got to read input file. Lab1.2 works on getting "any" input file to work.
#include <iostream>
#include <fstream>
#include <cstring>
int main()
{
using namespace std;
int key, length, count, i, j;
length = 35;
char filename[50];
fstream fin;
cout << "Enter a filename to open: " << endl;
cin >> filename;
fin.open(filename);
cout << "Enter number of integers to sort:" <<endl;
cin >> length;
char A[length];
for (count=0; count<length; count++)
{
fin >> A[count];
}
Here is the part that is troubling me. I can create the dynamic array up above using int *A = new int, but it needs a size, so *A = "a number" won't exactly work, and I'd still need something for the "for" loop as a maximum value.
I'm using "length" for the size of the array so i can feed the information from the named file to the array "A". I can't omit the size either way, but I'm stuck "in the box" of thinking on how to do it.
fin.close();
cout << "String Length: " << strlen(A) << endl;
for (j=2; j<length; j++)
{
key = A[j];
i=j-1;
while (A[i]>key && i>=0)
{
A[i+1]=A[i];
i=i-1;
}
A[i+1]=key;
}
ofstream fout;
fout.open("Sorted.txt");
cout << "Sorted List: ";
for (i=0;i<length; i++)
{
cout << A[i];
fout << A[i];
}
fout.close();
return 0;
}
I've been searching google, and I've heard of people recommending using vectors, malloc, and a few other things instead of new and delete, but since i'm only initializing once, i'd figure it'd be easy, eh?
oh, input from the file is in the form of "5123948021378041" so you just input the txt file name and then how many numbers you have in the file.
Anyways, any help or suggestions would be much much appreciated!