Reading files into a vector *CLOSED*
Mar 2, 2013 at 9:03pm UTC
Here the code of sorting by insertion. I am getting an 'out of range error'. How do I better read in the text file and store it in the Vector without running into this problem?
Thanks in advanced
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
cout << "What is the address of the file?" << endl;
getline(cin, file1);
ifstream textFile1 (file1);
//Tests the file
if (textFile1.fail())
{
cout << "File was not found" << endl;
system("PAUSE" );
exit (1);
}
else
cout << "\nFile opened successfully" << endl;
do
{
textFile1 >> insertion[count1];
count1 ++;
}while (!textFile1.eof());
//Insertion Sort1
for (first_unsorted1 = 1; first_unsorted1 < count1; first_unsorted1++)
{
if (insertion[first_unsorted1] < insertion[first_unsorted1 - 1])
{
position1 = first_unsorted1;
current1 = insertion[first_unsorted1];
do
{
insertion[position1] = insertion[position1 - 1];
position1--;
}while (position1 > 0 && insertion[position1 - 1] > current1);
insertion[position1] = current1;
}
}
Last edited on Mar 4, 2013 at 3:10pm UTC
Mar 3, 2013 at 1:27pm UTC
If you don't preallocate space in your vector you need to use push_back.
Change the following
1 2 3 4 5
do
{
textFile1 >> insertion[count1];
count1 ++;
}while (!textFile1.eof());
to
1 2 3 4 5 6
string str;
do
{
textFile1 >> str;
insertion.push_back(str);
}while (!textFile1.eof());
Mar 4, 2013 at 3:09pm UTC
Awesome! thanks so much
Topic archived. No new replies allowed.