4.20 Using Character Sets in Your HLA Programs


4.20 Using Character Sets in Your HLA Programs

Character sets are valuable for many different purposes in your programs. For example, one common use of character sets is to validate user input. This section will also present a couple of other applications for character sets to help you start thinking about how you could use them in your program.

Consider the following short code segment that gets a yes/no-type answer from the user:

 static      answer: char;           .           .           .      repeat                .                .                .           stdout.put( "Would you like to play again? ");           stdin.FlushInput();           stdin.get( answer );      until( answer = 'n' ); 

A major problem with this code sequence is that it will only stop if the user presses a lower case ‘n’ character. If they type anything other than ‘n’ (including upper case ‘N’) the program will treat this as an affirmative answer and transfer back to the beginning of the repeat..until loop. A better solution would be to validate the user input before the until clause above to ensure that the user has only typed "n", "N", "y", or "Y." The following code sequence will accomplish this:

 repeat           .           .           .      repeat           stdout.put( "Would you like to play again? ");           stdin.FlushInput();           stdin.get( answer );      until( cs.member( answer, { 'n', 'N', 'Y', 'y' } );      if( answer = 'N' ) then           mov( 'n', answer );      endif; until( answer = 'n' ); 

While an excellent use for character sets is to validate user input, especially when you must restrict the user to a small set of noncontiguous input characters, you should not use the cs.member function to test to see if a character value is within literal set. For example, you should never do something like the following:

 repeat      stdout.put( "Enter a character between 0..9: " );      stdin.getc(); until( cs.member( al, {'0'..'9' } ); 

While there is nothing logically wrong with this code, keep in mind that HLA run-time boolean expressions allow simple membership tests using the in operator. You could write the code above far more efficiently using the following sequence:

 repeat      stdout.put( "Enter a character between 0..9: ");      stdin.getc(); until( al in '0'..'9' ); 

The place where the cs.member function becomes useful is when you need to see if an input character is within a set of characters that you build at runtime.




The Art of Assembly Language
The Art of Assembly Language
ISBN: 1593272073
EAN: 2147483647
Year: 2005
Pages: 246
Authors: Randall Hyde

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net