开发者

C++ external file read: I know how to find and read a string, findMe. But how do I deal with findMei (finding any number, i, of the string)?

Apologies in advance, because I suspect this may be a silly question.

I have written a function for reading in data from an external file. I then use the data to perform calculations using other code I have written.

The function works by finding a data label that looks like this:

 const std::string findMe = "<dataLabel>";  

Each time I want to find data, I replace dataLabel with the label of whichever data I need from the file.

Here's what I want to do. I don't want to have to write in the label of the data I want each time. I want to be able to do this:

for (int i = 0; i < anyNumberOfDataSets; i++)  
{
    findMe = "<dataLabeli>"; 
    // Then run function for reading in data, put data into a vector.
}

I could then add any number of data sets to my external file, give each one the title , and have each data set read into a vector.

The problem is, I simply can't figure out how to write findMe = "<dataLabeli>". Is this even possible?

I have tried things li开发者_运维知识库ke, findMe = "<dataLabel" << i <<, but no luck!

Any suggestions would be much appreciated.


It is very hard to understand what you mean, but I guess you want this

#include <sstream>
#include <string>    

for (int i = 0; i < anyNumberOfDataSets; i++)  
{
    std::ostringstream strm;
    strm << "<dataLabel" << i << ">";
    const std::string findMe = strm.str();
    //...  
    //proceed with searching findMe     
}

You can read more about string streams, for instance, here


you've already got the right answer, so this is just trying to help you with solving such problems in the future:

Your core problem here is to convert the integer i into a string s (if you've done this, than you just do findMe = "<datalabel"; findMe += s; findMe += ">";.

Googling for c++ convert integer into string will give you this as the first result. Problem solved.

This is not saying "use google before/instead of asking", it's rather "try to identify the core problem".


Another solution:

using namespace boost;
findMe = str(format("<dataLabel%d>") % i);

This will substitute %d with the value of i, formatted like printf() does.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜