Hey!

Alright, I am working a program in C++ (obviously ;P).

I have been working on this game a very long time and took a break from it. I actually forgot how this line works:

vector<string> sWords(1);

int a = 0;

ifstream myfile("words.txt");

	if(!myfile) {
		cout << "Error opening words.txt\n";

		system("PAUSE");
	}
	while(!myfile.eof()) {
		[B]getline(myfile,sWords[a],' ');[/B]
		a++;
		sWords.resize(a+1);
	}

So what that does is that it reads words.txt and puts every word into a vector (the words are separated with a space). But I have completely forgotten how the bold text works...

I have found a lot of information of getline with google but I can't get a good explanation of how this works. I mean, it finds the spaces between the words and puts them into a vector?

getline() will return the entire line up to the '\n' character. That is not what you want. And the loop is wrong.

while( myfile >> words[a] )
   a++;

[edit]Well, the above is incorrect too because you are storing the words in a vector. Vectors do not auto expand when using indices as you posted so you need to use push_back() method to get that behavior.

std::vector< std::string > sWords;
std::string oneWord;
while( myfile >> oneWord )
    sWords.push_back(oneWord);

getline() will return the entire line up to the '\n' character. That is not what you want. And the loop is wrong.

while( myfile >> words[a] )
   a++;

[edit]Well, the above is incorrect too because you are storing the words in a vector. Vectors do not auto expand when using indices as you posted so you need to use push_back() method to get that behavior.

std::vector< std::string > sWords;
std::string oneWord;
while( myfile >> oneWord )
    sWords.push_back(oneWord);

I wouldn't say it's wrong because it works ;)

I'll look up push_back() though

http://www.dinkumware.com/manuals/default.aspx?manual=compleat&page=string2.html#getline
The third parameter is the delimiter character (when omitted, the delimiter is the newline character). So getline stops reading on a space (which it discards). Or, in a loop, tokens (word) are space-delimited.

Avoid Loop Control Using eof()

I'll be sure to read through that later, right now I have other things to do. Seems like a lot of good reading.

Thanks for helping!

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.