Hello Jaggy1997,
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.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
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.
You say:
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:
while(std::getline(fin, str))
. 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include <iostream>
#include <fstream>
#include <string>
//using namespace std; // <--- Best not to use.
const int MAX = 5;
int main()
{
std::string str;
std::ifstream fin;
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.
{
while (!fin.eof())
{
std::getline(fin, str);
std::cout << str << std::endl;
}
fin.close();
}
else {
std::cout << "unable to read from file!" << std::endl;
}
}
return 0;
}
|
That should be enough to keep you working for awhile. Any questions just ask.
Hope that helps,
Andy