I have to get the substring "Debian GNU/Linux 8 (jessie)" that is between two quotes, like:
PRETTY_NAME="Debian GNU/Linux 8 (jessie)"
But I don't know how to I can't manage to do that.
The best code I actually have:
std::ifstream osVersion("/usr/lib/os-release");
std::string os_str;
if (osVersion.is_open())
getline(osVersion, os_str);
osVersion.close();
this->os = os_str.substr(os_str.find("\""), os_str.find("\""));
It gives an output like that:
"Debian GNU/
The problem is when you do
this->os = os_str.substr(os_str.find("\""), os_str.find("\""));
find
is finding the same "
in each call. That means you are going to start your substring at the first "
and then it will be N
characters long where N
is the position of the first "
.
You can fix this by capturing the posistion of the first "
and using that to get the next one like
std::size_t pos = os_str.find("\"");
this->os = os_str.substr(pos + 1, os_str.find("\"", pos + 1) - pos - 1);
Do note though that in order to make the code bullet proof you should be capturing both positions and making sure the do not equal std::string::npos
If either of them do you have an improperly formatted sting and the above method will implode.
std::find
is easier to use here:
std::string::iterator begin = std::find(std::begin(os_str), std::end(os_str), '"');
if (begin != std::end(os_str)) {
++begin;
std::string::iterator end = std::find(begin, std::end(os_str), '"');
this->os = std::string(begin, end);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.