The reason is you reached the end of file when you count the length of the text thus the read pointer is at the end of the file and you used it again to read the text file.
To do it: Get the read pointer again to the beginning:
inFile.clear();
inFile.seekg(0, ios::beg);
while(inFile.get(message[i])){
i++;
}
Also don't use: while (!infile.eof())
it is considered to be incorrect.
What I recommend is to use std::vector
you don not mind about the file size or any allocation / de-allocation of memory. So your code can be like this:
std::ifstream inFile("data.txt"); // your file name here
std::string strLine;
std::vector<std::string> vecStr;
while(std::getline(inFile, strLine))
vecStr.push_back(strLine);
for(int i(0); i < vecStr.size(); i++)
std::cout << vecStr[i] << std::endl;
inFile.close();
Have you seen how the code is charm above?
- NB: You got the garbage values because the array is only declared but not initialized:
The first read gets the length of the text. But moved the read pointer to the end and then you did:
while(inFile.good() && !inFile.eof()){ // Will fail because inFile.eof() is true from the previous read.
//std::cout << "Inside the reading loop" << std::endl;
inFile.get(message[i]);
i++;
}
As you can see above the loop will not be executed because the previous read reached the eof
thus the array is just declared without being initialized thus as you know it contains garbage values.
To confirm that the loop is not executed un-comment the line above and see if the loop is executed. The result is no printing message which means it was not executed.