0

I received an assignment to take input from the user (a binary string representing a number) and to print the received number both in decimal and in hexadecimal.

I created an additional function in order to determine whether the input of the binary string is correct (includes only 1's and 0's) or not.

The code is working perfectly fine, except when I input the string in a certain fashion:

Let's say I input 11110000

The function runs smoothly.

But when I try to input 1111000 as the first string I enter, the function tells me that the string is invalid.

If I input the same string(1111000) after I input 11110000, it works just fine!

Attached is my function:

int CheckIfDigits1or0(char *NumString[MAX_SIZE_INPUT+2])
    {
        char digit;
        for (digit = *NumString; digit != '\0'; digit = *NumString++)
        {
            if (digit != '0' && digit != '1' && digit != '\n')
            {
                return 1;
            }
        }
        return 0;
    }

Help would be much appreciated!

2
  • 1
    In one line: if (strspn(str, "01") == strlen(str)) but remove any newline first. Commented Jun 25, 2020 at 17:48
  • 1
    char *NumString[MAX_SIZE_INPUT+2] is the problem. Wrong type. Post a minimal reproducible example. Commented Jun 25, 2020 at 17:48

1 Answer 1

2

You want to scan a string (a pointer to char), not an array of pointers to char:

int CheckIfDigits1or0(char *NumString[MAX_SIZE_INPUT+2])

should be

int CheckIfDigits1or0(char NumString[MAX_SIZE_INPUT+2])

or simply

int CheckIfDigits1or0(char NumString[]) // or char *NumString

Also, notice that we usually use return 1; for true and return 0; for false.

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

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.