在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;
}