Was testing this function in another cpp but it didn't work so I put it in a new cpp for testing, below is the code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
typedef vector<string> vstring;
vector<vstring> data;
void createDisplay();
bool checkFile(); //checks if the txt file is empty or not, if yes display "no data"
int main()
{
checkFile();
createDisplay();
cout << "The End"; //this doesn't shows up
return 0;
}
void createDisplay() //writes data from a txt file to 2d vector
{ //(12 rows fixated, total data are all multiples of 12)
//and display all of its contents
int i, j, k ,l;
ifstream file;
file.open("data.txt");
while (!file.eof()) {
for (int i = 0; i < 3; i++){
vector<string> tmpVec;
string tmpString;
for (int j = 0; j < 12; j++){
getline(file, tmpString);
tmpVec.push_back(tmpString);
}
data.push_back(tmpVec);
}
}
string line, tempStr;
while (getline(file, line))
{
data.push_back(vstring());
istringstream strm(line);
while (strm >> tempStr)
data.back().push_back(tempStr);
}
string list[12] = //list of items, tried splitting into two functions from here
{
"[1] A: ",
"[2] B: ",
"[3] C: ",
"[4] D: ",
"[5] E: ",
"[6] F: ",
"[7] G: ",
"[8] H: ",
"[9] I: ",
"[10] J: ",
"[11] K: ",
"[12] L: "
};
if (checkFile() == true)
{
for(k=0; k<12; k++)
{
cout << list[k] << "No data" << endl;
}
}
else
{
for(k=0;k<data[l].size();k++)
{
cout << list[k] ;
for(l=0;l<data.size();l++)
{
cout << left << setw(25) << data[l][k] ;
}
cout <<endl;
}
}
}
bool checkFile() //checks if the txt file is empty or not, if yes display "no data"
{
ifstream file;
file.open("data.txt");
if (file.peek() == ifstream::traits_type::eof())
return true;
else
return false;
}
Tested some cases,
Case 1: There is data in the txt file, data is successfully written into the vector, all data are displayed nicely, then programs stuns for a while, "The End" does not appear and the program ends.
Case 2: There is no data in the txt file, checkFile() works and displays "no data", "The End" appears.
I tried splitting createDisplay() into 2, one writing data into the vector, one displays content of vector, this round the program just stuns for a moment and ends without showing anything