C++ string to int

[复制链接]
 楼主| keer_zu 发表于 2024-2-23 17:24 | 显示全部楼层 |阅读模式
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;

  4. // Driver Code
  5. int main()
  6. {
  7.     string str = "2009, GeeksforGeeks_founded";
  8.     string str1 = "0x6C1";
  9.     string str2 = "-10010010101";

  10.     // Calling stoi() for all strings.
  11.     int num = stoi(str);
  12.     int num_hex = stoi(str1, nullptr, 16);
  13.     int num_bin = stoi(str2, nullptr, 2);

  14.     // printing converted values
  15.     cout << str << ": " << num << endl;
  16.     cout << str1 << ": " << num_hex << endl;
  17.     cout << str2 << ": " << num_bin << endl;

  18.     return 0;
  19. }



 楼主| keer_zu 发表于 2024-2-23 17:24 | 显示全部楼层
run~
  1. 2009, GeeksforGeeks_founded: 2009
  2. 0x6C1: 1729
  3. -10010010101: -1173




 楼主| keer_zu 发表于 2024-2-23 17:39 | 显示全部楼层
  1. #include <iostream>
  2. #include <string>
  3. #include <regex>
  4. using namespace std;

  5. string midstr(string oldstr, string startstr)
  6. {
  7.         string re = ".*?" + startstr + "(.*?)";
  8.         regex pattern(re);
  9.         smatch results;
  10.         if (regex_match(oldstr, results, pattern))
  11.                 return results[1];
  12.         else
  13.                 cout << "match failed: " << oldstr << endl;

  14. }


  15. int main()
  16. {
  17.         string text = "abc: 123456";
  18.         string data;
  19.         data = midstr(text, "abc:");
  20.         cout << data << endl;
  21.         int d = stoi(data.c_str());
  22.         cout << "data:" << d << endl;
  23.         //system("pause");
  24.         string str = "2009, GeeksforGeeks_founded";
  25.     string str1 = "0x6C1";
  26.     string str2 = "-10010010101";

  27.     // Calling stoi() for all strings.
  28.     int num = stoi(str);
  29.     int num_hex = stoi(str1, nullptr, 16);
  30.     int num_bin = stoi(str2, nullptr, 2);

  31.     // printing converted values
  32.     cout << str << ": " << num << endl;
  33.     cout << str1 << ": " << num_hex << endl;
  34.     cout << str2 << ": " << num_bin << endl;
  35.    
  36.     string estr  = "abc12";
  37.     try {
  38.             num = stoi(estr);
  39.    
  40.     } catch (const std::invalid_argument& ex) {
  41.         cout << "Invalid method id: " << ex.what() << endl;
  42.     }

  43.     string estr1  = "1233";
  44.      try {
  45.             num = stoi(estr1);
  46.    
  47.     } catch (const std::invalid_argument& ex) {
  48.         cout << "Invalid method id: " << ex.what() << endl;
  49.     }
  50.     cout << "num:" << num << endl;
  51. }

run~
  1. 123456
  2. data:123456
  3. 2009, GeeksforGeeks_founded: 2009
  4. 0x6C1: 1729
  5. -10010010101: -1173
  6. Invalid method id: stoi
  7. num:1233




您需要登录后才可以回帖 登录 | 注册

本版积分规则

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

1478

主题

12917

帖子

55

粉丝
快速回复 在线客服 返回列表 返回顶部