I have recently began programming and am having some difficulty resolving this problem:
The aim is to take in a binary number from a user, store it in a string then check each position to make sure it is only 1's 0r 0's entered. I cant seem to find a way to compare a variable containing either 1 or 0 to the value at the specified string position. Here is my code so far:
I have done quite a bit of reading trying to resolve this (I cant ask someone who would know just now either) but cant seem to find a specific answer. The outcomes from the IF statements are just for testing purposes just now, they will be altered when i can get the if's to work correctly.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string binary;
int i; //position in string
char a; //Value of binary[i]
int incorrect = 0;
//gets string
cout << "please enter a binary number:" << endl;
cin >> binary;
//end of string length
//To check the binary value
for(i = 0; i < binary.length(); i++) {
a = binary[i];
if (a == '0') {
cout << ".";
}
elseif (a == '1'){
cout <<".";
}
else {
cout << "x";
incorrect ++;}
}
//end of string input check
if (incorrect == 0) {
cout << endl << endl << "the input was in the correct format" << endl;
}
else {
cout << endl << endl << "you entered " << incorrect << " incorrect numbers" << endl;
}
}
I wanted to use variables which stored either 1 or 0 to compare to 'char a' during the if statements as we were told its good practice to use variables that can be called again instead of just a number/character. Any input on how this may be done would be appreciated so i can maybe try it that way to.
Yeh, what I said, if you defined zeroes and ones as:
1 2
ones = '1';
zeroes = '0';
You would be able to use the variables to compare. You were defining them as arrays, which is a different object type, so would never be equal.
I don't see why this would be "good practice", unless you were calling these variables in multiple places. Having them have a page of code up actually makes it less readable, as you don't know what you're actually comparing to, and there's always the chance the variable could be changed to something else.