I'm working on a c++ program and I need to take in a binary number from 0-255, inclusive, as a string(it has to be a string). What can I write in a while(input invalid) loop to check that the string is between 00000000 to 11111111, inclusive. Thanks so much
2 Answers
Assuming you use std::string:
while( str.length()==8 && str.find_first_not_of("01")==std::string::npos )
that is, if you really want it to be always 8 characters. Adjust to suit your taste (for what I can tell by your comment, you want str.length()<=8 or (!str.empty()) && str.length()<=8.
11 Comments
1111110000000, so the bug is not in the condition. Feel free to show your code if you can't find the error.I would suggest you to use std::bitset
if you string is always contain bits i.e. only **0 and 1 you u can use**
bitset<8> bitOfStr(string("01011")); // initialize from string bitset<8> bitOfStr(YourStringhere);
Note: If string contain anything else then 0/1 before length of bitset it will through an exception.
on bitset You can perform your rest of operations more efficiently .