2011-07-21 107 views

回答

7

您可以使用function 0Ah讀取緩衝輸入。給定一個字符串緩衝區中ds:dx它讀取的最大長度是255。緩衝器佈局是一個字符串:

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

讀取字符串,然後回聲回給用戶一個小COM文件的一個例子:

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 

注意,這將覆蓋輸入線(它可能因此不看程序做任何事情!)

或者您可以使用function 01h和自己在一個循環中讀取的字符。像這樣的東西(注意如果超過255個字符被輸入,它將溢出後面的緩衝區):

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 
+0

所以我可以讓'string db「$」'?它會起作用嗎? – AlbatrosDocsCoder

+0

如果你想要一個只包含'$'(ah = 09h函數的終止符)的單字節字符串,那麼是的,但是這樣就不會有任何地方存儲你讀的字符。 '時間255分貝'是相同的分貝0,0,0,0,[片段250次0,],0,這確保有空間來存儲字符。如果您使用不同的彙編程序,則預留空間的語法可能會不同(並且/或者您可以使用動態內存分配)。 – user786653

+0

多謝zou verz。 – AlbatrosDocsCoder

1

字符串只是一系列字符,因此您可以在循環內部使用int 21代碼來獲取一個字符串,一次一個字符。在數據段中創建一個標籤以保存字符串,並且每次讀取字符時,都將其複製到該標籤(每次增加一個偏移量,以便順序存儲字符)。當某個字符被讀取時停止循環(也許輸入)。

手動執行所有這些操作非常繁瑣(想想backspace是如何工作的),但是你可以做到。或者,您可以鏈接到stdio,stdlib等,並調用庫函數爲您完成大部分工作。

+0

非常感謝。但我不知道,如何做到。我知道它會像'mov啊,1h'一樣proc我 – AlbatrosDocsCoder

+0

我不能編輯該帖子。非常感謝你。但我不知道,如何做到這一切。我不知道如何在標籤中插入更多字符。所以我會有'字符串數據庫'$$$'',現在呢?我可以'mov string,al;按下的字符數據庫?如果是,比下一步做什麼?我不知道如何增加字符位置......你可以在這裏放置示例代碼嗎? – AlbatrosDocsCoder

+0

希望這對你仍然有用。您可以將內存位置保存在寄存器中,而不是使用標籤。這樣,您就可以寫入寄存器中的內存地址,而不是每次只寫入標籤。然後,當你修改地址寄存器(爲每個字符增加它),你將寫入新的內存位置。 – Quinn

相關問題