0

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

1
  • I know that I can convert each char in the string to an int and check that its 0/1 and make sure length is <= 8 but I was wondering if there was a quicker way I'm not thinking of Commented Sep 27, 2009 at 20:16

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

11 Comments

This works for rejecting something like 1111111111 but not for 11111100000000.
danny z, I'm not sure what you're trying to say. Your both examples will be rejected because they're longer than 8 characters.
What I meant was I just wrote the loop and checked it and it didn't reject 1111110000000
danny z, obviously the code above could not possibly accept 1111110000000, so the bug is not in the condition. Feel free to show your code if you can't find the error.
yeah the error has to be here: while(!input.empty() && input.length()<=8. && input.find_first_not_of("01")==std::string::npos); input is the string which contains the binary number. Thanks again for the help guys
|
0

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.