- Syntax: code% = ASC(character$)
- QB64 Syntax: code% = ASC(text$[, position])
- String character parameter must have a length of at least 1 byte or an error occurs. Cannot read empty strings.
- If the string used with ASC has more than one character, the first byte character code is returned.
- Code INTEGER values returned will range from 0 to 255 only.
- ASC will create an error if reading an empty string ("") returned in an INKEY$ loop when there is no keypress!
- ASC returns 0 when reading 2 byte codes returned by INKEY$ when the arrow, funtion, central keys or certain combination keyboard presses are used.
- In QB64 a new parameter is allowed; position, the ASCII code of the character in the character position specified will be returned by the function (if omitted ASC will return the code of the first character).
65 66 67
Explanation: The ASCII code for "A" is 65 and the ASCII code for "B" is 66, ASCII code for "C" is 67 and the "C" is at position 18 in the string.
Note: The ASCII code for "A" and "a" are different by the value of 32, "A" + 32 is "a", 65("A") + 32 = 97("a").
Example 2: Reading only numerical values input by a program user.
DO: SLEEP ' requires a keypress to run loop once K$ = INKEY$ code = ASC(K$) IF code >= 48 AND code <= 57 THEN entry$ = entry$ + CHR$(code) ' numbers only IF code = 46 AND flag = 0 THEN entry$ = entry$ + K$: flag = 1: mark = LEN(entry$) ' decimal point END IF L = LEN(entry$) ' check entry length for possible backspace IF code = 8 AND L > 0 THEN ' backspace pressed and entry has a length entry$ = MID$(entry$, 1, L - 1) ' remove one character from entry$ IF L - 1 < mark THEN flag = 0 ' allow another decimal point if removed. LOCATE 10, POS(0) - 1: PRINT SPACE$(1); ' remove character from screen END IF LOCATE 10, 10: PRINT entry$; ' display present entry to user(semicolon required for correct POS return) LOOP UNTIL code = 13 AND L
Explanation: SLEEP waits for a keypress allowing background programs to use the processor time. It also keeps the press in the keyboard buffer for INKEY$ to read and guarantees that ASC will not read an empty string value to create an error. Filtered codes 48 to 57 are only number characters. One decimal point is allowed by using the flag. Code 8 is a backspace request which is ignored if the entry has no characters. If it is allowed it removes the last character from the entry and the screen. The loop exits when the user presses the [Enter] key and the entry has a length. Try to do that with INPUT!