打印

C++ string to int

[复制链接]
595|2
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
keer_zu|  楼主 | 2024-2-23 17:24 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
#include <iostream>
#include <string>
using namespace std;

// Driver Code
int main()
{
    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;

    return 0;
}



使用特权

评论回复

相关帖子

沙发
keer_zu|  楼主 | 2024-2-23 17:24 | 只看该作者
run~
2009, GeeksforGeeks_founded: 2009
0x6C1: 1729
-10010010101: -1173




使用特权

评论回复
板凳
keer_zu|  楼主 | 2024-2-23 17:39 | 只看该作者
#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




使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

个人签名:qq群:49734243 Email:zukeqiang@gmail.com

1352

主题

12436

帖子

53

粉丝