开发者

How to make string input in Assembly language?

Please, does anybody know how to code string input in assembly开发者_StackOverflow中文版 language? I'm using int 21 to display and input characters.


You can use function 0Ah to read buffered input. Given a string buffer in ds:dx it reads a string of up to length 255. The buffer layout is:

Byte 0 String length (0-255)
Byte 1 Bytes read (0-255, filled by DOS on return)
Bytes 2-..Length+2 (The character string including newline as read by DOS).

An example of a small COM file that reads a string and then echos it back to the user:

    org 0x100

start:
    push cs
    pop ds ; COM file, ds = cs

    mov ah, 0x0A ; Function 0Ah Buffered input
    mov dx, string_buf ; ds:dx points to string buffer
    int 0x21

    movzx si, byte [string_buf+1] ; get number of chars read

    mov dx, string_buf + 2 ; start of actual string

    add si, dx ; si points to string + number of chars read
    mov byte [si], '$' ; Terminate string

    mov ah, 0x09 ; Function 09h Print character string
    int 0x21 ; ds:dx points to string

    ; Exit
    mov ax, 0x4c00
    int 0x21

string_buf: 
    db 255 ; size of buffer in characters
    db 0 ; filled by DOS with actual size
    times 255 db 0 ; actual string

Note that it will overwrite the input line (and it thus might not look the program is doing anything!)

Alternatively you can use function 01h and read the characters yourself in a loop. Something like this (note it will overflow later buffers if more than 255 characters are entered):

    org 0x100

start:
    push cs
    pop ax
    mov ds, ax
    mov es, ax; make sure ds = es = cs

    mov di, string ; es:di points to string
    cld ; clear direction flag (so stosb incremements rather than decrements)
read_loop:
    mov ah, 0x01 ; Function 01h Read character from stdin with echo
    int 0x21
    cmp al, 0x0D ; character is carriage return?
    je read_done ; yes? exit the loop
    stosb ; store the character at es:di and increment di
    jmp read_loop ; loop again
read_done:
    mov al, '$'
    stosb ; 'Make sure the string is '$' terminated

    mov dx, string ; ds:dx points to string
    mov ah, 0x09 ; Function 09h Print character string
    int 0x21

    ; Exit
    mov ax, 0x4c00
    int 0x21

string: 
    times 255 db 0 ; reserve room for 255 characters


A string is just a series of characters, so you can use your int 21 code inside of a loop to get a string, one character at a time. Create a label in the data segment to hold your string, and each time you read a character, copy it to that label (incrementing an offset each time so your characters get stored sequentially). Stop looping when a certain character is read (perhaps enter).

Doing all this manually is tedious (think about how backspace will work) but you can do it. Alternatively, you can link against stdio, stdlib, etc. and call library functions to do much of the work for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜