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