getting words from a file to store in string vector

I'm trying to write a program to extract words from a text file and store them as strings in a vector of type string. When I try to execute it, the program hangs indefinitely. There are no visible syntax errors, and I have no idea what's wrong.
Any help would be appreciated. Here's The code:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

void getFile(ifstream infile, vector<string> &words);


int _tmain(int argc, _TCHAR* argv[])
{
ifstream infile;
vector<string> words;

getFile(infile, words);

return 0;
}

void getFile(ifstream infile, vector<string> &words)
{
infile.open("gettysburg.txt");
if(infile.fail())
{
cout << "Error: Failed to open file." << endl << "Exiting." <<endl;
exit(1);
}
string str;

while(!infile.eof())
{
while(infile >> str);
{
words.push_back(str);
}
infile.close();
}
cout << "There are " << words.size() << " words in the file." << endl;
}
Code tags and indentation are prerequisites to help in the vast majority of cases.
Also, you know that stdafx is not necessary in that case right? stdafx is just an MSFT precomp'd header for the ones people use a lot.
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
38
39
40
41
42
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

void getFile(ifstream infile, vector<string> &words); //reads file and stores words in a vector of type string.


int _tmain(int argc, _TCHAR* argv[])
{
	ifstream infile;
	vector<string> words;
	
	getFile(infile, words);

	return 0;
}

void getFile(ifstream infile, vector<string> &words)
{
	string str;

	infile.open("gettysburg.txt");
	if(infile.fail())
	{
		cout << "Error: Failed to open file." << endl << "Exiting." <<endl;
		exit(1);
	}
	

	while(!infile.eof())
	{
		while(infile >> str);
		{
		words.push_back(str);
		}
		infile.close();
    }
		cout << "There are " << words.size() << " words in the file." << endl;
}
OK, let's see... perhaps you should close infile after you are finished with it, rather than after.... Well I don't really understand the nesting on that second loop. You can streamline that to, in pseudocode (at least I think this should work)
1
2
3
4
5
6
while (get a string from infile)
{
    add the string to your vector
} // at this point you've extracted everything you can already
// so only now should you close it with
infile.close();

OK, so that was quasipseudocode. But you see what I mean, right? When infile reaches the EOF, the test will be unsuccessful (the while infile >> str) and then you can close it. You can check this for more data, and because I am probably wrong: http://www.cplusplus.com/doc/tutorial/files/
Topic archived. No new replies allowed.