-4

im studiying basics of c++. i want to display a .txt file of ANSI form through C++,but it only displays 25 lines; what to do to display large text files like 100 lines long?

the code i use now is :

char c[15];
ifstream f("file.txt",ios::in);
f.seekg(0);
while(!f.eof())
{f>>c;
cout<<c;
}
getch();
f.close(); 

2 Answers2

4

Try this:

std::string text;
while (std::getline(f, text))
{
  std::cout << text << std::endl;
}

Don't use character arrays, as they can overflow.

In your code, you are limited to 15 characters per read because of the size of the array.

The f >> c may overrun your array, as you haven't told the system how many characters to read.

See also Why eof in a loop is bad

Community
  • 1
  • 1
Thomas Matthews
  • 52,985
  • 12
  • 85
  • 144
  • I was with you right up until [`endl`](http://chris-sharpe.blogspot.co.uk/2016/02/why-you-shouldnt-use-stdendl.html)! (Also, `using namespace std;`?) – BoBTFish Feb 02 '17 at 15:16
  • @BoBTFish: I added the `std::` prefix. The `endl` is to flush the buffer every line; a newbie thing. – Thomas Matthews Feb 02 '17 at 15:20
  • 2
    Yes, that's exactly why I *don't* like teaching it to newbies. Too many newbies think it is the only "right" way to stream out a newline. When I see it in code, I can only ever assume it was used incorrectly. Like here. Do you *really* want to flush every line? And if so, be explicit about it (`std::flush`). – BoBTFish Feb 02 '17 at 15:22
1

Read Why is iostream::eof inside a loop condition considered wrong?

If you must use character array as buffer, then you should use the std::istream::read with its size. It's going to require more work to get that right.

You should probably prefer:

#include <iostream>
#include <fstream>
#include <string>

int main(){
    std::ifstream file("file.txt");
    for(std::string line; std::getline(file, line);)
        std::cout << line << '\n';
}
Community
  • 1
  • 1
WhiZTiM
  • 19,970
  • 3
  • 36
  • 56