【问题标题】:Binary Literals in C++C++ 中的二进制字面量
【发布时间】:2020-11-02 11:21:57
【问题描述】:
我可以在用户输入 int 值之前在 c++ 中添加二进制字面量前缀吗?
#include <iostream>
using namespace std;
int main () {
int n1;
cin>>n1;
string s1 = to_string(n1);
string s2 = "0b";
string s=s2+s1;
int n=stoi(s);
cout<<n;
return 0;
}
我试过这个但失败了,因为 stoi() 只读取 0 并跳过其余部分
【问题讨论】:
标签:
c++
string
binary
integer
literals
【解决方案1】:
仍然无法直接从标准输入读取二进制数。任何基数的自动检测都不支持"0b",因此当达到'b' 时stoi() 停止。
如果s 是从标准输入读取的std::string(可能是std::cin >> s;),没有 "0b" 前缀,那么您可以使用
#include <cstdlib>
char* end;
long n = std::strtol(s.c_str(), &end, 2/*radix of 2 denotes binary*/);
检查指针end 以防s 中有无效的二进制数字。
请注意,我使用的是 strtol 而不是 stoi,因为 int 的上限可以小至 32767。