how can i skip the 1st 2 lines from my input file

Dani AI

Generated

As asked about skipping the first two lines and suggested reading line-by-line, the two safest, common patterns in C++ are: (A) discard whole lines with std::getline, or (B) discard until the next newline with istream::ignore. Both handle normal text files; choose (A) for line-oriented logic and (B) when mixing formatted extraction and raw line discards.

A — discard two full lines with getline:

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

std::ifstream in("input.txt");
if (!in) { std::cerr << "Cannot open file\n"; return 1; }

std::string line;
for (int i = 0; i < 2 && std::getline(in, line); ++i) { /* skipped */ }

while (std::getline(in, line)) {
    // process remaining lines
}

B — discard up to newline using ignore (useful after using operator>>):

#include <fstream>
#include <limits>

std::ifstream in("input.txt");
if (!in) return 1;

in.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // drop first line
in.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // drop second line
// continue reading from 'in'

Notes and pitfalls: mixing operator>> and std::getline often leaves a stray newline in the stream — call ignore(...) once to remove it before using getline. If the goal is to skip exactly two newline characters (not two lines), use in.get() twice but check for EOF. For Windows CRLF issues, remove a trailing '\r' from line if present. Always check return values from getline/get to avoid processing when the file has fewer than two lines.

Recommended Answers

All 5 Replies

Member Avatar for Member #46692

>how can i skip the 1st 2 lines from my input file

Read file in line by line
 If line number equals 1 or 2 
   then 
     //ignore
   endif
 else
  //do other stuff

do u know how 2 make cin>> with \n , i mean the syntex 2 write it
i want 2 make only 2 \n

Member Avatar for Member #46692

To read in a line, assuming your file is a plain text file, you can use
cin.getline() or getline - assuming you read in each line as a std::string.

i don't understand what do u mean.
do u know the \n
and the ignore function

Member Avatar for Member #46692

If you don't know what getline is then maybe you should google it?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.