在C++中,可以使用以下方法将string转换为int:
#include <string>
#include <iostream>
int main() {
std::string str = "123";
int num = std::stoi(str);
std::cout << num << std::endl;
return 0;
}
#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;
}
#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,可以使用以下方法:
#include <string>
#include <iostream>
int main() {
int num = 123;
std::string str = std::to_string(num);
std::cout << str << std::endl;
return 0;
}
#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;
}
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: c++ complex类的性能优化有哪些方法