我能在用户输入的整数值前添加二进制字面量前缀吗?
#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并跳过其余部分。
目前仍无法直接从标准输入读取二进制数。任何基数的自动检测都不支持"0b"
,因此stoi()
会在遇到'b'
时停止。
如果从标准输入读取了一个std::string
(例如:std::cin >> s;
),没有带有"0b"
前缀,那么你可以使用
#include <cstdlib>
char* end;
long n = std::strtol(s.c_str(), &end, 2/*radix of 2 denotes binary*/);
在检查s
中是否有无效的二进制数字时,需要检查指针end
。
请注意,我使用strtol
而不是stoi
,因为int
的上限可以小至32767。