Word swallowing function

Very basic question but I do not know how to word it enough to search the forum or google it. Tried "eats word" etc. Basically, my code eats the first word of my getline. example below.The jokeF function is meant to read from a file with a single line, the punchLineF function is meant to read ONLY the last line in a file But the punchLineF function does not the display the very first word, just the rest. How can I fix this? what am I doing wrong?
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
  #include <iostream>
#include <fstream>
using namespace std;


void jokeF(fstream &file)
{
	string joke;
	getline(file, joke);
	cout << joke;
	
	cin.ignore();
	cin.get();


}

void punchLineF(fstream &file)
{

	string punchLine;
	while ( file >>  punchLine)
		getline(file, punchLine);

	cout << punchLine;		

}
int main()

{
	string fileName1,fileName2, data;

	fileName1 = "c:\\joke.txt";
	fileName2 = "c:\\punchline.txt";
	
	fstream dataFile1, dataFile2;
	
	dataFile1.open(fileName1.c_str() , ios::in);
	dataFile2.open(fileName2.c_str() , ios::in);

	
	jokeF(dataFile1);
	punchLineF(dataFile2);
	return 0;
}
1
2
3
4
5
6
7
8
9
void punchLineF(fstream &file)
{

    string punchLine;
    while ( getline(file, punchLine) )
        ;

    cout << punchLine;		
}


You were reading a word into punchline, then extracting the rest of the line into punchline, overwriting the word you had just extracted.

The above could be problematic if your file ends with an empty line.
Last edited on
Topic archived. No new replies allowed.