1.11M Members

How do I allow a string to contain only the values 0 and 1?

 
0
 

Hi, I'm a bit of a newbie to Pascal and I'm trying to create a simple program to convert binary numbers to decimal, I'm unsure of how I can disallow an input that is not binary, this is my code:

var
 Validation : boolean;
 Binary, Number : String;
 Decimal, index, a, ConvertedBin, BinaryA, error : Integer;

begin
 repeat
  Writeln ('Please enter a binary number for it''s decimal conversion: ');
  readln (Binary);
  If Length(Binary) <= 8 then
  Validation := TRUE
   else validation := FALSE;
   If(Binary[index] in ['0'..'1'])
  then
  Validation := TRUE
   else Validation := FALSE;
 If Validation = FALSE then writeln ('Invalid input.');
 until Validation = TRUE;
  Number := Binary;
  Decimal := 0;
  BinaryA := 0;
  for a := Length(Binary) downto 0 do
  begin
    If BinaryA > 0 then BinaryA := BinaryA * 2
   else BinaryA := 1;
    Val (Binary[a], ConvertedBin, error);
    Decimal := Decimal + (ConvertedBin * BinaryA);
  end;
    writeln ('This is your binary number, ', Number, ', in decimal form: ',Decimal);
    readln;
end.

The warning I get is : Variable 'index' might not have been initialized
I'm just unsure of how to get this part of the code to work:

 If(Binary[index] in ['0'..'1'])
  then
  Validation := TRUE
   else Validation := FALSE;

Please help if you can! Thanks :)

 
0
 

index is never given a value. I think you should be using a for loop to loop through each character entered.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: