#include <iostream>
#include <string>
#include <regex>
using namespace std;
string midstr(string oldstr, string startstr)
{
string re = ".*?" + startstr + "(.*?)";
regex pattern(re);
smatch results;
if (regex_match(oldstr, results, pattern))
return results[1];
else
cout << "match failed: " << oldstr << endl;
}
int main()
{
string text = "abc: 123456";
string data;
data = midstr(text, "abc:");
cout << data << endl;
int d = stoi(data.c_str());
cout << "data:" << d << endl;
//system("pause");
string str = "2009, GeeksforGeeks_founded";
string str1 = "0x6C1";
string str2 = "-10010010101";
// Calling stoi() for all strings.
int num = stoi(str);
int num_hex = stoi(str1, nullptr, 16);
int num_bin = stoi(str2, nullptr, 2);
// printing converted values
cout << str << ": " << num << endl;
cout << str1 << ": " << num_hex << endl;
cout << str2 << ": " << num_bin << endl;
string estr = "abc12";
try {
num = stoi(estr);
} catch (const std::invalid_argument& ex) {
cout << "Invalid method id: " << ex.what() << endl;
}
string estr1 = "1233";
try {
num = stoi(estr1);
} catch (const std::invalid_argument& ex) {
cout << "Invalid method id: " << ex.what() << endl;
}
cout << "num:" << num << endl;
}
run~
123456
data:123456
2009, GeeksforGeeks_founded: 2009
0x6C1: 1729
-10010010101: -1173
Invalid method id: stoi
num:1233
|