954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Search sub-string in vector and write whole string to file

Hello,

I'm having a problem with finding and printing an element in a vector.

I want to search my vector to see if an element starts with a sub-string, and if it does, I want to write the whole string to a file.
The first part is done, I just can't figure out how to write the whole string to file.

Here's my code:

ifstream file1(filename);
std::vector<std::string> load;
for(std::string line1; getline(file1, line1); )
	{
		load.push_back(line1);
	}

	for(int i = 1; i < 1018; ++i)
	{
		std::ostringstream integer;
		integer << "IDS_STRING" << i << "\t";
		std::string thisString = integer.str();
		bool isPresent = std::find_if(load.begin(), load.end(), StartsWith(thisString)) != load.end();
		if(isPresent == true)
		{
			RC << ??? + "\n";
		}
	}
}
struct StartsWith {
    const std::string val;
    StartsWith(const std::string& s) : val(s) {}
    bool operator()(const std::string& in) const
    {
        return in.find(val) == 0;
    }


I've put '???' where I'm having trouble, which is what to put for the output so that the entire element (not just the first part I searched for) is written to the file (RC).

Any ideas/suggestions would be much appreciated.

ahoysailor
Newbie Poster
14 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

find_if returns an iterator. You should compare that to load.end () if you want to see if it succeeded. Then just use the iterator.

std::vector<std::string>::iterator vit = std::find_if(load.begin(), load.end(), StartsWith(thisString));
if (vit != load.end ()) {
   // do what you want with the iterator here
}
L7Sqr
Practically a Master Poster
657 posts since Feb 2011
Reputation Points: 201
Solved Threads: 124
 

Thanks! That works perfectly. This is how I implemented it:

for(int i = 1; i < 1018; ++i)
{
	std::ostringstream integer;
	integer << "IDS_STRING" << i << "\t";
	std::string thisString = integer.str();
	bool isPresent = std::find_if(load.begin(), load.end(), StartsWith(thisString)) != load.end();
	if(isPresent == true)
	{
		std::vector<std::string>::iterator vit = std::find_if(load.begin(), load.end(), StartsWith(thisString));
		if (vit != load.end ()) 
		{
			RC << *vit + "\n";
		}
	}
}


Works great, thank you!

ahoysailor
Newbie Poster
14 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: