I am a CS1 student and have had no issues until this point in the class really. I have been working on this for awhile now and cannot figure out how to get this to work!
I am supposed to use this code and modify it to #1 - open a .DAT file (which is just a comma delimited file with about 15 numbers) #2 - import the numbers from the file #3 - Sort the numbers
We are supposed to keep with the existing code using vectors but I just cannot get this to function properly...this is my very first post here so be easy with me lol
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>
usingnamespace std;
bool myfunction (int i,int j) { return (i<j); }
struct myclass {
booloperator() (int i,int j) { return (i<j);}
} myobject;
int main () {
ifstream file ( "DATA.DAT" );
string temp;
vector<int> myvector;
vector<int>::iterator it;
file.open("DATA.DAT"); //open data file
while(!file.eof())
{
getline(file, temp);
cout << temp << '\n';
myvector.push_back(temp);
}
file.close();
// using default comparison (operator <):
sort (myvector.begin(), myvector.begin()+4);
// using function as comp
sort (myvector.begin()+4, myvector.end(), myfunction);
// using object as comp
sort (myvector.begin(), myvector.end(), myobject);
// print out content:
cout << "The file contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it;
cout << endl;
return 0;
}
I know that there are a few lines that are probably way off, but I am pulling my hair out because everything I have tried hasn't worked...any help would be greatly appreciated.
The file isn't reading in at all. I have not been able to get it to read in correctly.
This code was mostly provided by the professor and I have run it (minus trying to bring in the file) and it sorted the array correctly. So I am assuming it is an issue with the file and getting the contents in order to sort.
We learned about basic array sorting which I didn't have any issues with, but working with vectors and the comma delimited file threw me for a loop...
You need to make sure the file is in the working directory. I would change your file handling to something like this:
1 2 3 4 5 6 7 8
ifstream file ( "test.txt" , ifstream::in ); //You may need to change the open mode for the DAT
while (file .good())
{
getline(file , temp);
cout << temp << '\n';
myvector.push_back(atoi(temp.c_str())); //Don't forget your vector is int
}
file .close();