I am making a statistics collector that reads the log of a music player and lets the user show top ten most played etc. As a noob project.
A line from the log looks like: "20:42:03 start E:\ROTATION\A\Håkan Lidbo - Dammlunga.mp3"
I have put this in a string using ifstream and getline.
Then making an array of chars of the string using
const char *charveqtur = newline.c_str();
Then I tried to sort i out with sscanf:
sscanf (charveqtur, "%d:%d:%d\tstart\t%s", &this->hour, &this->minute, &this->second, &this->filename);
The problem is that the filename is cut at the first space. I have also tried using istringstream instead but no breakthrough so far.
Which is the most convinient way of doing this? Thanks.
You can use some input stream to read the first integers and colons, and because the filename is the last entity, you can then use
std::getline
. However, even if your filename is not the last part, note thatstd::getline
is quite a versatile function that accepts any delimiter.A more advanced method would be to define your own type for filenames and overload
operator>>(std::istream &, T const &)
on it.Here is a complete example using
std::getline
andstringstream
with basic diagnostics and some reformatting:Output:
Important: When parsing, you are sailing close to the security risks. Always be conscious and sensible and try to use tested and proven libraries where possible. This also implies that you do not use
sscanf
, which is not typesafe, error-prone and sometimes hard to get right.Don't use C if you have C++, and used correctly, iostreams are even more convenient than printf/scanf+co.