c++ 11字符串与string转换常用函数

  这里主要介绍一下string to int 其他方法与这个类似,可到头文件 <string> 中查看
     @_Str 转换的字符串
 @_Idx 转换的长度(位数)  @_Base 进制
  • double stod(const string& _Str, size_t *_Idx = nullptr);
  • float stof(const string& _Str, size_t *_Idx = nullptr);
  • int stoi(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
  • long stol(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
  • long double stold(const string& _Str, size_t *_Idx = nullptr);
  • unsigned long stoul(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
  • long long stoll(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
  • unsigned long long stoull(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
     std::string y = "253647586946334221002101219955219971002";
	int x;
 
	try {
		x = stoi(y);
	}
	catch (std::invalid_argument&){
		// if no conversion could be performed
		cout << "Invalid_argument" << endl;
	}
	catch (std::out_of_range&){
		// if the converted value would fall out of the range of the result type 
		// or if the underlying function (std::strtol or std::strtoull) sets errno 
		// to ERANGE.
		cout << "Out of range" << endl;
	}
	catch (...) {
		// everything else
		cout << "Something else" << endl;
	}
	return 0;
  • string to_string(int _Val);
  • string to_string(unsigned int _Val);
  • string to_string(long _Val); string
  • to_string(unsigned long _Val);
  • string to_string(long long _Val);
  • string to_string(unsigned long long _Val);
  • string to_string(float _Val);
  • string to_string(double _Val);
  • string to_string(long double _Val);

可以看到 to_string(); 方法不仅支持各种整型( 有符号的、无符号的、长的、短的 任意组合 ),还支持各种浮点型( float/double 包括长的、短的 )

 

猜你喜欢

转载自www.cnblogs.com/wsw-seu/p/13377048.html