We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,985 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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

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 :)

2
Contributors
1
Reply
3 Hours
Discussion Span
3 Months Ago
Last Updated
11
Views
Niatia
Newbie Poster
1 post since Feb 2013
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

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

pritaeas
Posting Prodigy
Moderator
9,287 posts since Jul 2006
Reputation Points: 1,173
Solved Threads: 1,458
Skill Endorsements: 86

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0585 seconds using 2.71MB