为何#include<cstdlib>中的atoi()函数在二进制字符串转整数时失效?
问题分析与解决:二进制字符串转整数失败
你遇到的问题有两个核心原因:
atoi()的参数类型不匹配:它要求传入C风格字符串(const char*),但你直接传递了std::string对象,这会导致编译错误。- 即使类型问题解决了,
atoi()是按十进制规则解析字符串的,无法识别二进制格式,得到的结果会完全不符合预期。
解决方法1:使用C++标准库的std::stoi(推荐)
C++11及以上标准提供了std::stoi函数,支持指定解析的基数(传入2表示二进制),同时可直接接受std::string参数:
#include <iostream> #include <string> using namespace std; int main() { int num, n; string r; cout << "Enter the number : "; cin >> num; while(num != 0){ r = (num%2 == 0 ? "0" : "1") + r; num /= 2; } cout << "\nBinary value is " << r << endl; // 使用stoi指定二进制基数 n = stoi(r, nullptr, 2); cout << n << endl; return 0; }
解决方法2:手动实现二进制转整数逻辑
如果不想依赖C++11及以上特性,可以遍历字符串手动计算:
#include <iostream> #include <string> using namespace std; int main() { int num, n = 0; string r; cout << "Enter the number : "; cin >> num; while(num != 0){ r = (num%2 == 0 ? "0" : "1") + r; num /= 2; } cout << "\nBinary value is " << r << endl; // 逐位计算二进制转整数 for(char c : r){ n = n * 2 + (c - '0'); } cout << n << endl; return 0; }
解决方法3:使用C风格函数strtol
如果坚持用C风格函数,可使用strtol(支持指定基数),需传入C风格字符串:
#include <iostream> #include <string> #include <cstdlib> using namespace std; int main() { int num, n; string r; cout << "Enter the number : "; cin >> num; while(num != 0){ r = (num%2 == 0 ? "0" : "1") + r; num /= 2; } cout << "\nBinary value is " << r << endl; // 传入C风格字符串并指定二进制基数 n = static_cast<int>(strtol(r.c_str(), nullptr, 2)); cout << n << endl; return 0; }
内容的提问来源于stack exchange,提问作者Nancy_it_is
相关产品推荐
相关产品推荐

