As others have said, you are likely reading past the end of the file as you're only checking for x != ' '
. Instead you also have to check for EOF in the inner loop (but in this case don't use a char, but a sufficiently large type):
while ( ! file.eof() )
{
std::ifstream::int_type x = file.get();
while ( x != ' ' && x != std::ifstream::traits_type::eof() )
{
word += static_cast<char>(x);
x = file.get();
}
std::cout << word << '\n';
word.clear();
}
But then again, you can just employ the stream's streaming operators, which already separate at whitespace (and better account for multiple spaces and other kinds of whitepsace):
void readFile( )
{
std::ifstream file("program.txt");
for(std::string word; file >> word; )
std::cout << word << '\n';
}
And even further, you can employ a standard algorithm to get rid of the manual loop altogether:
#include <algorithm>
#include <iterator>
void readFile( )
{
std::ifstream file("program.txt");
std::copy(std::istream_iterator<std::string>(file),
std::istream_itetator<std::string>(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}