i'm making a program in c++ that gets a binary number and converts it to an integer. But of coarse i've hit a snag, I need a way to store a binary number that's any length, then run through the number to see if a 2 or something is there, if it is then to ask for a new number. Here is what I thought would work, but of coarse, it doesn't. (it's not completed, i just wanted to see if i could find out if they entered something other than a one or zero here):

int binToDec()
     {
     string binaryToConv = ("0");
     bool reEnter = false;
 
     cout << "Enter a binary number to convert: " << endl;
     cin >> binaryToConv;
 
     for(int counter = 0; ;counter += 1)
         {
         reEnter = false;
         if((binaryToConv[counter] != 0) && (binaryToConv[counter] != 1))
              {
              reEnter = true;
              break;
              }
         if(counter == binaryToConv.size())
             {
              break;
             }
        }
        if(reEnter = true)
             {
              binToDec();
              }
     cout << "adsf";
     }

Dani AI

Generated

Nice progress so far. Two points that nobody has clarified yet: string characters are characters, so compare to '0' and '1' (not 0 and 1), and stop loops with index < s.size() so you don't read past the end. Building on ideas from and about validating first and about avoiding recursion for simple input retries, here are safe conversion options and a few practical tips.

If the result fits in an unsigned long long, scan left-to-right and use multiply-by-two plus the bit, checking for overflow before each step:

#include <string>
#include <stdexcept>
#include <limits>

unsigned long long binToULL(const std::string& s) {
    if (s.empty()) throw std::invalid_argument("empty string");
    unsigned long long val = 0;
    for (char c : s) {
        int bit = c - '0'; // requires prior validation that c is '0' or '1'
        if (val > (std::numeric_limits<unsigned long long>::max() - bit) / 2)
            throw std::overflow_error("too large for unsigned long long");
        val = val * 2 + bit;
    }
    return val;
}

For arbitrarily long binaries, use a bigint type and the same shift-add loop. With Boost.Multiprecision it looks like:

#include <boost/multiprecision/cpp_int.hpp>

boost::multiprecision::cpp_int binToBig(const std::string& s) {
    using boost::multiprecision::cpp_int;
    cpp_int val = 0;
    for (char c : s) val = (val << 1) + (c - '0');
    return val;
}

Practical checklist: read the whole line (std::getline) and trim whitespace, reject empty input, validate each char is '0' or '1' before conversion, avoid recursion for retries (use a loop), and decide whether to drop leading zeros or report overflow. These steps will make validation and conversion robust for both small and very large binary inputs.

Recommended Answers

All 5 Replies

Something tells me you're missing a = here:

if(reEnter = true)
             {
              binToDec();               }

Also, when you know that the number isn't true, you break out of the loop before the statement I just showed gets executed. Which brings up another point: why are you using recursion for a simple input validation?

I need to check if the number they enter only has ones and zeros. Also, once it's been validated, i'll need to go through every single digit from last to first for the conversion, but the part I want to get done now is just the validation part. You asked why I was using recursion, what should I be using?

You could try something like this:

bool validInput = true;
 
cout << "Enter a binary number to convert: " << endl;
cin >> binaryToConv;
 
int len = binaryToConv.length();

for(int counter = 0; counter < len; ++counter)
{
   if((binaryToConv[counter] != 0) && (binaryToConv[counter] != 1))
   {
       validInput == false;
       break;
   }
}

if (validInput)
  binToDec(binaryToConv);
else
  //retry input

Why try to reinvent the wheel when you can do something like....

int main ( )
{
    using namespace std ;

    string my ;
    const char* const valid_char = "01" ;
    bool valid = true ;

    cout << "Please enter a string: " ;
    cin >> my ;
    getchar( ) ;

    if( my.length() == 0 || 
                my.find_first_not_of( valid_char ) != string::npos)
    {
        valid = false ;
    }

    if( valid )
        cout << "Ready for conversion..." ;
    else
        cout << "Please enter a binary number.." ;

    getchar( ) ;
    return 0 ;
}

Thank you very much guys, I've been trying to get this to work for two days and now I've got the first part done, woo! Now to attempt the manual conversion...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.