【C++类型转换】string 与 int 类型之间的转换以及string 与 char*、char[]转换

一、string 与 int

1. string 转换为 int:

解决方法之一:利用std::stoi()、stol()、stoll()函数 OR std::strtol()...

//(1)The Function Prototype
  //int  stoi(const std::string& str, std::size_t* pos = 0, int base = 10);

  //show an example of stoi function
  // Define an integer variable
  int i_temp = 100;
  string str_temp = "2019ewrabc";
  std::string::size_type size_type_temp = 3;
  int i_strToi = std::stoi(str_temp, &size_type_temp,16);

  cout << size_type_temp << endl;
  // the output is 5;
  //If pos is not a null pointer, then a pointer ptr - internal to the conversion functions - will
  //receive the address of the first unconverted character in str.c_str(),
  //and the index of that character will be calculated and stored in *pos, 
  //giving the number of characters that were processed by the conversion.
 
  cout << i_strToi << endl;
  //the output is 131486

  //(2)The Function Prototype
  //std::strtol(str.c_str(), &ptr, base)
  char* stop;
  int i_strtol = strtol(str_temp.c_str(), &stop,16);
  cout << i_strtol << endl;// output is 131486
  cout << stop << endl;// output is wrabc

  
  i_strtol = strtol(str_temp.c_str(), &stop,0);
  cout << i_strtol<<endl;// output is 2019
  cout << stop << endl;// output is ewrabc

解决方式之二:用sstream中定义的字符串流对象来实现

【C++类型转换】string 与 int 类型之间的转换以及string 与 char*、char[]转换

(图片来源于其他博客,侵权删)

int i_temp4 ;
  string str_temp="2000";
  stringstream stream2;
  stream2 << str_temp;
  stream2 >> i_temp4;
  cout << i_temp4 << endl<<typeid(i_temp4).name();
//output is 2000 int

2.int 转换为 string 

解决方法:利用to_string()方法

//int to string 
  int i_temp2 = 100;
  string str_temp2 = std::to_string(i_temp2);
  cout << str_temp2;

解决方法:用sstream中定义的字符串流对象来实现

 int i_temp3 = 100;
  string result;
  stringstream stream;
  stream << i_temp3;
  stream >> result;
  cout << result << endl<<typeid(result).name();

二、string 与 char、 char*

见博客:https://blog.csdn.net/steft/article/details/60126077