Getline prints extra line from text file

Hi, im new to C++ and im very confused as to why does the getline prints the extra content after I split the string with a delimiter also is there a better way for me to split the string instead of multiple getlines?


#include <iostream>
#include <string>
#include <fstream>
#include "unit.h"

using namespace std;

int main()
{
ifstream inFile("input.txt");
Unit u;
string temp;

while(getline(inFile, temp))
{
getline(inFile, temp, ' ');
cout << temp << endl;
}
}

Actual Output:
Data_Structures
Security_Policy
Foundation_Programming
ICT159 4 75 30 April 2017

Expected output:
Data_structures
Security_Policy
Foundation_Programming

Text file:
102234 962 4
Data_Structures ICT283 3 50 30 June 2016
Security_Policy ICT380 1 80 30 December 2016
Foundation_Programming ICT159 4 75 30 April 2017
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <fstream>
//#include "unit.h"

using namespace std;

int main()
{
	ifstream inFile("input.txt");
	//Unit u;
	string temp;

	while (getline(inFile, temp))
	{
		if (getline(inFile, temp, ' ')) {
			cout << temp << endl;
		}
	}
}

use this code, have try.
Last edited on
Because you are using the same variable in both your getline() functions your program will produce different output depending on whether or not the input file's last line has a new line character or not.

I suggest you put a breakpoint at the while() statement then single step through the loop with your debugger, watching the values of the variables as you step.

Or try something like to "see" the problem:

1
2
3
4
5
6
    while(getline(inFile, temp))
    {
        cout << "Before second getline(): " << temp << ' ';
        getline(inFile, temp, ' ');
        cout << "After second getline(): " << temp << endl;
    }


If you used a string stream and different variables then it won't matter if the last line has an end of line character or not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <fstream>

int main() {
	std::ifstream inFile("input.txt");

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

	// First read 'header' line
	for (std::string first; !std::getline(inFile, first); );

	for (std::string temp; inFile >> temp; std::getline(inFile, temp))
		std::cout << temp << '\n';
}



Data_Structures
Security_Policy
Foundation_Programming

Topic archived. No new replies allowed.