Converting from Java to C++ Reading a File, and parsing
The Text file looks like this:
Apple,Itunes,1,7.3
Microsoft,Windows Media Player,1,10
.... and so on.....
The parse method i开发者_如何学Cs:
private IApplication parseLineToApp(String lineFromTxtFile) {
Scanner lineScanner = new Scanner(lineFromTxtFile);
lineScanner.useDelimiter(",");
return new Application(lineScanner.next(), lineScanner.next(), lineScanner.nextInt(), lineScanner.next());
}
I want to do the same thing in c++ to create a new application(). Note: I already have an application class, and need to add that application to a repository which is a collection of applications
Thanks in advance :)
You can create a vector of strings using Boost and the STL.
// given std::string lineFromTxtFile
std::vector<std::string> scanner;
boost::split (scanner, lineFromTxtFile, boost::is_any_of(","));
return new Application (scanner[0], scanner[1], scanner[2], scanner[3]);
If you want scanner[2]
to be an integer, there's
boost::lexical_cast<int> (scanner[2])
File operations can be done a few different ways in C/C++. A C++-style approach could look like the following:
std::vector<Application> ApplicationList;
std::ifstream fin("myapplist.txt"); // open a file stream
while (!fin.eof()) // while this isn't the end of the file
{
char buffer[256] = {0};
fin.getline(buffer, 256); // read the current line of text into the buffer
std::vector<std::string> scanner;
boost::split(scanner, buffer, boost::is_any_of(",")); // split the buffer and store the results in the scanner vector
ApplicationList.push_back(Application(scanner[0], scanner[1], scanner[2], scanner[3]); // add the application to the application list
}
fin.close();
Assuming your Application struct/class is copyable (otherwise you'd want to use pointers in your ApplicationList).
There is no Scanner class in the C++ standard library, the direct translation is not possible. Of course, you can always implement your own.
Alas, you could create a split function:
unsigned int split(const std::string &txt, std::vector<std::string> &strs, char ch)
{
size_t pos = txt.find( ch );
size_t initialPos = 0;
strs.clear();
if ( pos != std::string::npos ) {
// Decompose each statement
strs.push_back( txt.substr( initialPos, pos - initialPos + 1 ) );
initialPos = pos + 1;
pos = txt.find( ch, initialPos );
while( pos != std::string::npos ) {
strs.push_back( txt.substr( initialPos, pos - initialPos + 1 ) );
initialPos = pos + 1;
pos = txt.find( ch, initialPos );
}
}
else strs.push_back( txt );
return strs.size();
}
Then you could rewrite your code as:
std::vector<std::string> scanner;
split( lineFromTxtFile, scanner, ',' );
return new Application (scanner[0], scanner[1], scanner[2], scanner[3]);
Hope this helps.
精彩评论