hello, I was wondering if anyone could look at this code for me and tell me what I need to do to get the array working. My problem is that I am reading a text file and I need to make an array that will size up to the text file while we do not know how big it is. What am I doing wrong here?
int main()
{
ifstream infile;
ofstream outfile;
int x = 100000;
int num[x];
//open a data file, set infile to read from it
infile.open("random1000.txt");
outfile.open("sorted.txt");
while (!infile.eof())
infile >> num[x];
x++;
//if you are a good programmer
//you will always remember to close
//your files (even though it doesn't matter)
infile.close();
outfile.close();
return 0;
}
int main()
{
ifstream infile;
ofstream outfile;
int *a, x;
//open a data file, set infile to read from it
infile.open("random1000.txt");
outfile.open("sorted.txt");
a = newint[x];
while (!infile.eof())
{
infile >> a[x];
x++;
}
infile.close();
outfile.close();
return 0;
}
I suggest you count how many numbers are in your file before creating your array. Then read the file a second time putting the numbers into the correctly sized array.
EOF is only set *after* you try to read past the end of the file. It is not set simply by reaching the end of the file. So by testing for eof() before you do the read >> you don't know if the read >> was successful or not.
int main()
{
ifstream infile;
ofstream outfile;
int *a = NULL, x = 1000, y = 0;
//open a data file, set infile to read from it
infile.open("random1000.txt");
outfile.open("sorted.txt");
while(!infile.eof()) // To get you all the lines.
{
infile >> a[x];
y++;
}
a = newint[x];
//while (!infile.eof())
//{
// infile >> a[x];
// x++;
//}
infile.close();
outfile.close();
return 0;
}
{
ifstream infile;
ofstream outfile;
int *a = NULL, x = 1, y = 0;
//open a data file, set infile to read from it
infile.open("random1000.txt");
outfile.open("sorted.txt");
a = newint[x];
while(!infile.eof()) // To get you all the lines.
{
infile >> a[x];
y++;
}
a = newint[x];
infile.open("random1000.txt");
while (!infile.eof())
{
infile >> a[x];
x++;
}
infile.close();
outfile.close();
return 0;
}
int main()
{
ifstream infile;
ofstream outfile;
int *a = NULL, x = 1, y = 0;
//open a data file, set infile to read from it
infile.open("random1000.txt");
outfile.open("sorted.txt");
a = newint[x];
while(!infile.eof()) // To get you all the lines.
{
infile >> a[x];
cout<<a[x]<<endl;
y++;
}
a = newint[y];
x = 0;
int b = 0;
while (x<y)
{
infile >> a[b];
b++;
x++;
cout<<a[b]<<endl;
}
mysterySort(a, y);
for(int z = 0; z < x; z++)
{
outfile<<a[z]<<endl;
}
infile.close();
outfile.close();
return 0;
}