The check for eof in the while loop does not work. You will find tons of pages in SO explaining this. One example has been given by Nate Eldredge in the comment above: Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?.
Additionally, I recommend to use more modern C++ language elements. With that, you can avoid all the nitty gritty stuff.
See the below example:
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <iterator>
std::istringstream testFile(R"(Lorem ipsum dolor sit amet,
consetetur sadipscing elitr, sed diam nonumy eirmod tempor
invidunt ut labore et dolore magna aliquyam erat, sed diam
voluptua. At vero eos et accusam et justo duo dolores et ea
rebum. Stet clita kasd gubergren, no sea takimata sanctus est
)");
int main() {
std::copy_if(std::istream_iterator<std::string>(testFile),{},
std::ostream_iterator<std::string>(std::cout, "\n"),
[](const std::string& s) { return (0x208222 >> (s[0] & 0x1f)) & 1; });
return 0;
}
As you can see, the whole task can be accomplished with one copy_if()
statement.
And, it doesn't matter, where the data is coming from. At the moment, I am using a std::istringstream
. But, you can also open a file and put the std::ifstream
variable into the std::istream_iterator
. Same with the output. At the moment, I am writing to std::cout
. You can put an open std::ofstream
variable here as well.
So, now to std::copy_if()
. Please see here for the description. copy_if()
takes 2 input iterators for the begin and end of the source, an output iterator, and a condition.
The istream_iterator
will basically call the extractor operator>>
and extracts std::string
s from the stream. It will be called, until the end of the file is hit (or an error occurs). The end iterator is given by the empty brace default initializer. And if you look here, you will see that the default constructor is equal to the end iterator.
For writing the data we will use std::ostream_iterator
, which will write all copied strings to the output stream.
For the condition in the std::copy_if()
, we use a lambda, which checks if the first character of the string is a vowel.
The algorithm to detect a vowel has been described by me in detail here.
So, very simple. Just one statement necessary.