PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.
|So we can have 1000 lines in there but it is only gonna print out 10 lines in a row.|
OK which ten lines? The first ten? The last ten? Or a random ten? Printing the first tn is easy.
Your program has most of the right pieces, but will not work this way.
Your while loop condition is not the way to check for end of file. Checking for "eof" does not work the way you think it will. The while loop will print out 1001 lines not the 1000 in the file. By the time the while conditions understands that you have reached "eof" the last line read will print twice. The more common way of writing the while condition is:
. This way when the stream fails so does the while loop.
If you only want to print ten lines the while loop needs away to count the number of lines printed and break out of the while loop when the count has reached ten.
The for loop in unnecessary because it will print the ten lines you need five times before it is finished. Not what you want.
The following code is yours and has some notes in worth reading:
//using namespace std; // <--- Best not to use.
const int MAX = 5;
for (int i = 0; i < MAX; i++)
fin.open("DataTextFile.txt"); // <--- Should be above for loop.
if (fin.is_open()) // <--- This check should be done above for loop.
std::cout << str << std::endl;
std::cout << "unable to read from file!" << std::endl;
That should be enough to keep you working for awhile. Any questions just ask.
Hope that helps,