我正在尝试从具有以下格式的语义版本字符串中提取3个数字:"v%d.%d.%d"
这是我的示例代码:
std::string myVersion = "v3.49.1";
int versionMajor, versionMinor, versionPatch;
getVersionInfo(myVersion, versionMajor, versionMinor, versionPatch);
std::cout << versionMajor << " " << versionMinor << " " << versionPatch << '\n';
预期结果:
3 49 1
如何设计功能getVersionInfo()
?
最优雅的解决方案是什么?
答案 0 :(得分:1)
使用sscanf:
void getVersionInfo(std::string version, int &major, int &minor, int &patch) {
sscanf(version.c_str(), "v%d.%d.%d", &major, &minor, &patch);
}
答案 1 :(得分:1)
也许您可以尝试
#include <iostream>
using namespace std;
int main() {
string s="v3.49.1";
int major,minor,patch;
int x=s.find(".");
//We dont want v symbol so start from 1 till 1st dot
major=stoi(s.substr(1,x));
cout<<major;
//Then find second dot from first symbol and copy as sub string
int y=s.find(".",x+1);
minor=stoi(s.substr(x+1,y-x));
cout<<minor;
//After that remaining string will be patch version
patch=stoi(s.substr(y+1));
cout<<patch;
return 0;
}