How to ignore the last line of a file

Hi, I am stuck on one part that I could not figure out.
How do you not read in the last line of a file into your program? I tried looping but that did not work if I used a different file with a different file length.

Thanks, any suggestion helps.
Sorry, don't have a code to share.

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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ifstream fin("input_file.txt");
    if (!fin)
    {
        cerr << "Couldn't open input file.\n";
        return 1;
    }

    string line1, line2;

    if (!getline(fin, line1))
        return 0; // empty file

    while (getline(fin, line2))
    {
        // process line1
        cout << line1 << '\n';

        swap(line1, line2);
    }
}

Last edited on
sorry, but can you explain how this reads in the file, but not the last line?
Think about it.

Note that instead of the swap it could be:

 
line1 = line2;

But with strings, the swap is more efficient due to move semantics.
Last edited on
Hello QianIsHere,

Just a different thought:
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
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <iomanip>
#include <string>
#include <limits>

#include <fstream>

int main()
{
    const std::string inFileName{ "Data.txt" };

    std::ifstream inFile(inFileName);

    if (!inFile)
    {
        std::cerr << "\n File " << std::quoted(inFileName) << " did not open" << std::endl;
	
        return 1;
    }

    int linesInFile{};
    std::string line;

    while (std::getline(inFile, line))
    {
        linesInFile++;
    }

    std::cout << "\n The file contains " << linesInFile << " lines.\n\n";

    inFile.clear();
    inFile.seekg(0);

    for (int lc = 0; lc < linesInFile - 1; lc++)
    {
        std::getline(inFile, line);

        std::cout << std::setw(2) << lc + 1 << "  " << line << '\n';
    }

	// <--- Keeps console window open when running in debug mode on Visual Studio. Or a good way to pause the program.
	// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
	//std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
	std::cout << "\n\n Press Enter to continue: ";
	std::cin.get();

	return 0;  // <--- Not required, but makes a good break point.
}

Not knowing what your input file looks like you may have to adjust the while loop and I have no idea how you would have to read the file, but the idea should work.

I tested with this input file:

Enrique Thomas
Londyn White
Maverick Chan
Susan Dixon
Ariella Leonard
Zaniyah Shah
Jaylah Nielsen
Rolando Roy
Devyn Cobb
Eliezer Mcpherson


And have the output of:

The file contains 10 lines.

 1  Enrique Thomas
 2  Londyn White
 3  Maverick Chan
 4  Susan Dixon
 5  Ariella Leonard
 6  Zaniyah Shah
 7  Jaylah Nielsen
 8  Rolando Roy
 9  Devyn Cobb


 Press Enter to continue:


When you have a file of unknown length, sometimes you first have to find how many line you have to work with first.

Andy
this reads in the file, but not the last line


The last line needs to be read in some way - to know that the end-of-file has been reached. IMO the OP doesn't want to process the last line. This can be done either as per dutch's code, andy's (but that code has the performance penalty of reading the file twice, which may or may not be an issue depending upon the file size), or the last line is unique in some way which can be tested as part of the processing.

There is also the technique of reading the whole file into say a vector<string> and removing the last element. Another method would be to read the whole file into say a string and remove trailing chars up-to a '\n'.

Depending upon the size of the file and the processing requirement, would help determine the way forward.
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
   ifstream fin( __FILE__ );
   string line[2];
   if ( !getline( fin, line[0] ) ) return 0;
   for ( int num = 1; getline( fin, line[num] ); num = 1 - num ) cout << line[1-num] << '\n';
}
Last edited on
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
// Process all but a particular number of last lines, ignoring blank lines.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

const int Skip = 2; // Number of last non-blank lines to skip

istream& get_nonblank_line(istream& in, string& line)
{
    while (getline(in, line) && line.find_first_not_of(" \t") == line.npos)
        ;
    return in;
}

int main()
{
    ifstream fin("input_file.txt");
    if (!fin)
    {
        cerr << "Couldn't open input file.\n";
        return 1;
    }

    string lines[Skip + 1];

    for (int i = 0; i < Skip; ++i)
        if (!get_nonblank_line(fin, lines[i]))
            return 0; // less than Skip non-blank lines in file

    for (int next = Skip; get_nonblank_line(fin, lines[next]); )
    {
        next = (next + 1) % (Skip + 1);
        cout << lines[next] << '\n';
    }
}

Last edited on
By reading the whole file into a string:

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
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>

int main()
{
	std::ifstream ifs("input_file.txt");

	if (!ifs.is_open())
		return (std::cout << "Cannot open file\n"), 1;

	ifs >> std::noskipws;

	std::string data((std::istream_iterator<char>(ifs)), std::istream_iterator<char>());

	data.resize(data.find_last_not_of("\t\n"));
	data.resize(data.find_last_of('\n'));

	std::istringstream iss(data);

	for (std::string line; std::getline(iss, line); )
		// Process line here
		std::cout << line << '\n';
}



Given input file as before:


Enrique Thomas
Londyn White
Maverick Chan
Susan Dixon
Ariella Leonard
Zaniyah Shah
Jaylah Nielsen
Rolando Roy
Devyn Cobb
Eliezer Mcpherson


displays:


Enrique Thomas
Londyn White
Maverick Chan
Susan Dixon
Ariella Leonard
Zaniyah Shah
Jaylah Nielsen
Rolando Roy
Devyn Cobb

Topic archived. No new replies allowed.