温馨提示×

C++中string与int相互转换的方法是什么

c++
小亿
126
2023-07-28 09:34:01
栏目: 编程语言

在C++中,可以使用以下方法将string转换为int:

  1. 使用stoi函数:stoi函数将字符串转换为int类型,如果字符串无法转换为int,会抛出一个异常。
#include <string>
#include <iostream>
int main() {
std::string str = "123";
int num = std::stoi(str);
std::cout << num << std::endl;
return 0;
}
  1. 使用stringstream类:可以使用stringstream类进行流化操作,将字符串转换为int类型。
#include <string>
#include <iostream>
#include <sstream>
int main() {
std::string str = "123";
std::stringstream ss(str);
int num;
ss >> num;
std::cout << num << std::endl;
return 0;
}
  1. 使用c_str()函数和atoi函数:c_str()函数将字符串转换为C风格的字符串,然后使用atoi函数将C风格字符串转换为int类型。
#include <string>
#include <iostream>
#include <cstdlib>
int main() {
std::string str = "123";
const char* cstr = str.c_str();
int num = std::atoi(cstr);
std::cout << num << std::endl;
return 0;
}

要将int转换为string,可以使用以下方法:

  1. 使用std::to_string函数:to_string函数将int类型转换为string类型。
#include <string>
#include <iostream>
int main() {
int num = 123;
std::string str = std::to_string(num);
std::cout << str << std::endl;
return 0;
}
  1. 使用stringstream类:可以使用stringstream类进行流化操作,将int类型转换为string类型。
#include <string>
#include <iostream>
#include <sstream>
int main() {
int num = 123;
std::stringstream ss;
ss << num;
std::string str = ss.str();
std::cout << str << std::endl;
return 0;
}

0