Joshua Holmes
Joshua Holmes

Reputation: 13

c++ binary to decimal converter input to only accept 1 or 0

Hello I am trying to do a programming assignment that converts a binary number to a decimal. The problem states that I have to get the users input as a sting and if there is anything other than a 1 or a 0 in the users input it should give an error message then prompt them to give a new input. I have been trying for a while now and I cant seem to get it right can anyone help me? so far this is my best attempt it will run every input of the string into a if statement but it only seems to care about the last digit i cant think of a way to make it so if there is a single error it will keep while loop statement as true to keep going.

#include <iostream>
#include <string>
using namespace std;

string a;

int input();

int main()
{
    input();
    int stop;
    cin >> stop;
    return 0;
}

int input()
{
    int x, count, repeat = 0;

    while (repeat == 0)
    {
        cout << "Enter a string representing a binary number => ";
        cin >> a;
        count = a.length();
        for (x = 0; x < count; x++)
        {

            if (a[x] >= '0' &&a[x] <= '1')
            {
                repeat = 1;
            }
            else
                repeat = 0;
        }

    }

    return 0;
}

    return 0;
}

Upvotes: 0

Views: 1281

Answers (1)

mcleod_ideafix
mcleod_ideafix

Reputation: 11438

Change your for loop as this:

    count = a.length();
    repeat = 1;
    for (x = 0; x < count; x++)
    {

        if (a[x] != '0' && a[x] != '1')
        {
            repeat = 0;
            break;
        }
    }

The idea is that repeat is assumed to be 1 at first (so you assume that your input is valid). Later on, if any of your input characters is not a 0 or 1, then you set repeat to 0 and exit the loop (there's no need to keep looking for another character)

Upvotes: 2

Related Questions