要将字符串可移植转换为不常见的整数类型,可以使用以下方法:
stoi
或stoll
函数。stoi
函数将字符串转换为int
类型,而stoll
函数将字符串转换为long long
类型。这些函数可以处理不同进制的数字,例如二进制、八进制和十六进制。#include<iostream>
#include<string>
#include <stdexcept>
int main() {
std::string str = "1010";
try {
int num = std::stoi(str, nullptr, 2);
std::cout << "The binary string "<< str << " is equivalent to the integer "<< num<< std::endl;
} catch (std::invalid_argument &e) {
std::cout << "Invalid argument: " << e.what()<< std::endl;
} catch (std::out_of_range &e) {
std::cout << "Out of range: " << e.what()<< std::endl;
}
return 0;
}
istringstream
类。这种方法可以处理任何基数的数字,并且可以处理负数。#include<iostream>
#include <sstream>
#include<string>
#include <stdexcept>
int main() {
std::string str = "1010";
int base = 2;
int num;
std::istringstream iss(str);
iss >> num;
if (iss.fail()) {
std::cout << "Failed to convert string to integer"<< std::endl;
} else {
std::cout << "The "<< base << " string "<< str << " is equivalent to the integer "<< num<< std::endl;
}
return 0;
}
boost::lexical_cast
函数。这种方法可以将任何可以转换为整数类型的字符串转换为整数类型。#include<iostream>
#include<string>
#include<boost/lexical_cast.hpp>
int main() {
std::string str = "1010";
try {
int num = boost::lexical_cast<int>(str);
std::cout << "The string "<< str << " is equivalent to the integer "<< num<< std::endl;
} catch (boost::bad_lexical_cast &e) {
std::cout << "Failed to convert string to integer: " << e.what()<< std::endl;
}
return 0;
}
这些方法可以将字符串可移植转换为不常见的整数类型。
领取专属 10元无门槛券
手把手带您无忧上云