【STL】String的几种常见的类型转换

#include <iostream>
#include <boost/lexical_cast.hpp> 

int main(int argc, char *argv[], char *env[])
{
	// 1. c++中string到int的转换
	// 1.1 在标准库里面,使用atoi或者strtol
	{
		std::string text = "152";
		int number = std::atoi(text.c_str()); 
		std::cout << number << std::endl;
	}

	// 1.2 在Boost库里面,使用lexical_cast
	try
	{
		std::string text = "100000000";
		int number = boost::lexical_cast<int>(text);
		std::cout << number << std::endl;
	}
	catch(const boost::bad_lexical_cast &e)
	{
		//转换失败
		std::cout << e.what() << std::endl;
	}               

	// 2. char*转string
	{
		char *c = "Test char!!!";
		std::string str(c);
		std::cout << str << std::endl;
	}

	// 3. string转char*
	{
		std::string str = "Test String!!!";
		const char *c = str.c_str();
		std::cout << c << std::endl;
	}
	
}


你可能感兴趣的:(C++,c,String,include)