Hello,

I am having some trouble reading data from a .txt file. I know that the file contains strings separated by white space. The problem is, I don't know how many strings there are, so I would like to go through the file one string at a time, and then store each string into a vector or something similar such that they can be accessed. My question is, is this doable with the getline() function, or is there some other function that does this?

getline can do this.

getline will read the entire line, then you'll have to break up the line read into its individual strings.
Alternatively, you can use >> to read in each individual string. >> will stop reading at whitespace.

#include <iostream>
#include <fstream>

using namespace std;


int main(int argc, char **argv)
{
	fstream fin;
	std::string word;
	std::string testfile = "./mary.txt";

	fin.open(testfile.c_str(), ios::in);

	if (fin.is_open()) {
		std::getline(fin, word, ' ');
		cout << word << endl;
	}
}

./mary.txt

mary had a little lamb, little lamb, little lamb,
she had a little lamb, alright?
a frickin lamb.

output:

[sovereign@tetramorph ~]# g++ try.cpp 
[sovereign@tetramorph ~]# ./a.out 
mary
[sovereign@tetramorph ~]#

How would I go about using the >> operator? More to the point, how does it know to move on to the next string? Something like this:

std::string temp1, temp2;
while (!file.eof()) {
file >> temp1 >> temp2; //to read the first two strings
//etc...
}

I can see that working if I know how many strings there are; can it still work even if I don't know ahead of time how many strings are in the file?

It shouldn't matter, just loop to the end of the file, and add each string to the vector, like so:

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;


int main(int argc, char **argv)
{
	std::vector<std::string> words;
	fstream fin;
	std::string word;
	std::string testfile = "./mary.txt";

	fin.open(testfile.c_str(), ios::in);

	if (fin.is_open()) {

		while (std::getline(fin, word, ' ')) {
			words.push_back(word);
		}

		fin.close();
	}

	for (int i=0; i < words.size(); i++) {
		cout << words[i] << endl;
	}

	return 0;
}

Now, The Vector "words" will contain every word in the file (though I think that last new line is hanging around in there... you should be able to just trim that off though). Now you can loop through the vector, or whatever you need to do with each word.

Yeah, thanks alot, you wrote your reply as I was replying to the post above yours; I like your way best, thanks much. :P

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.