I\'m trying to read in numbers from a file and putting them into an array. Right now when I run the program it prints 8 numbers, then the line ends and prints the same 8 nu
I don't know what your file contains or how it would cause an infinite loop printing more than the last number. However, the eof()
bit is only good for error reporting but not
for loop control. Also, there is a lot of other stuff in the code which is utterly unnecessary. The following program should read the numbers OK:
#include
#include
int main()
{
std::ifstream infile("euler8Nums.txt");
for (int num; infile >> num; )
std::cout << num << "\n";
return 0;
}
I never saw a point in calling open()
separately unless there is a conditional necessary necessary before the file name can be worked out. Likewise, calling close()
explicitly seems to be pretty pointless unless you want to check that the close was successful (although I'm unsure if close()
on an input stream has an opportunity to fail).
Another of my pet peeves is the unnecessary use of std::endl
: this manipulator is a relatively frequent source of bad performance! It does two things:
\n
(or, on wide character streams the result of widening this character).Only flush the stream when you really mean to. If you feel that you need extra flushes on your stream, e.g. when trying to find what is written right before a crash, just set std::unitbuf
on the stream object: this will be worse from a performance point of view because it flushes the stream after each insertion but it is easily removed once the problem is located.
Of course, the resulting program can be changed to something even neater like
#include
#include
#include
#include
int main()
{
std::copy(std::istream_iterator(std::ifstream("euler8Nums.txt") >> std::ws),
std::istream_iterator(), std::ostream_iterator(std::cout, "\n"));
}