Can I add binary literal prefix in c++ before a user input int value.
#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;
}
I tried this but failed as stoi() only reads 0 and skips the rest
There's still no way of reading a binary number directly from standard input. Any auto-detection of the radix does not support "0b", so stoi() stops when 'b' is reached.
If s is a std::string read from standard input (std::cin >> s; perhaps), without the "0b" prefix, then you can use
#include <cstdlib>
char* end;
long n = std::strtol(s.c_str(), &end, 2/*radix of 2 denotes binary*/);
checking the pointer end in case there are invalid binary digits in s.
Note that I'm using strtol rather than stoi as an int can have a upper limits as small as 32767.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With