Only just started using vectors and pretty clueless with them! anyway... I am grabbing all file names in a directory with a .txt file extension. Storing those files in string vector named listOfFiles.
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 36 37
|
//Prototype Functions
string Filter(string & str, char, char);
void calcAndShowResults(int, float, int , float, float);
void getFileNames(std::vector<std::string> *fileList);
//Main Function
int main ()
{
std::vector<std::string> listOfFiles; // No pointer
getFileNames(&listOfFiles);
for ( int i = 0; i < 9; i++)
{
//Opening HH for reading
ifstream handHistory;
handHistory.open (listOfFiles[i]) ;
//Close Program if unable to open HH
if (! handHistory.is_open () )
{
cout << "Unable to open " << endl;
i = 8;
}
//Array for the lines of text
string Line[4];
//Loop each line of text and then store it in the Line array
for (int x = 0; x < 4; x++)
{
getline (handHistory, Line[x]);
}
//Close HH now we have grabbed the data we need
handHistory.close();
}
}
|
And the function to grab the filenames and store them in a vector.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
//GetFileNames Function
void getFileNames(std::vector<std::string> *fileList)
{
WIN32_FIND_DATA search_data;
memset(&search_data, 0, sizeof(WIN32_FIND_DATA));
HANDLE handle = FindFirstFile("C:\\test folder\\*.txt", &search_data);
while(handle != INVALID_HANDLE_VALUE)
{
fileList->push_back(std::string(search_data.cFileName));
if(FindNextFile(handle, &search_data) == FALSE)
break;
}
}
|
So i use a loop of 8 because I have 8 text files in the folder with names , text1.txt , text 2.txt , text 5.txt , text 22.txt etc (not in sequential order) but I want to be able to open the first text file , grab 4 lines of text , store it in a string array, close the file , (do some calculations which i left out) then open the next file.
So in theory i in the loop is 0 on the first run so open listOfFiles[0] (text1.txt) grab the 4 lines , run calculations , close it, next loop i = 1 so grab listOfFiles[1] (text2.txt) grab 4 lines etc etc...
Now the problem I have is when I use a cout in the loop for testing the value of listOfFiles[i] it should be (text1.text) but instead it lists all of the text files but when I write
cout << listOfFiles[0];
it correctly displays just the first text file name.
I think the part of the error is because the vector is trying to fstream open all the files at once hence the subscript out of range. How do I write it so the loop value of i is what the correct filename from the listOfFiles is? On the other hand though when I tell it to
handHistory.open (listOfFiles[0]) ;
It still throws the same error so it might not be that :(
I have copied the files from the test directory into the project directory so the files are all there.