-3

I'm new to programming, so I was wondering...

If I have an input file consisting of 100 lines, how do I read only up to line 50 and print out each line?

Thanks.

  • 2
    Use a variable to keep track of many lines you've read and stop when it is equal to 50. – wally May 01 '16 at 02:25
  • 2
    If you've tried and have a specific issue post an example of the issue and the code – Cameron637 May 01 '16 at 02:26
  • 1. Take and initialize a counter to zero (to count the number of lines you read) 2. Use a loop and continue it until the counter value is 50 3. Inside loop read a line from file and increment the counter by 1 – Monirul Islam Milon May 01 '16 at 14:41
  • 1
    Possible duplicate of [How to read line by line or a whole text file at once?](http://stackoverflow.com/questions/13035674/how-to-read-line-by-line-or-a-whole-text-file-at-once) – Gary May 01 '16 at 16:50

2 Answers2

0

Please use 'fstream' to read your file and count each 'readline'. Each 'readline' means a full line which terminated with '\n'(return value without it). That should be useful.

Gemini Keith
  • 910
  • 6
  • 17
0
  1. create a fstream object fstream f("filename");
  2. Keep a counter, read lines from file till the counter less than 50 Something like this

      counter = 0;
      while((counter < 50) && (f.good())
      {
         getline(f,str);
         cout<<str<<endl;
         counter++
      }
    

    Note: this is not the full code, but guideline how to do.

Jfevold
  • 414
  • 2
  • 11
Varun
  • 297
  • 2
  • 9