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.

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
}

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!

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.