2017-11-02 51 views
2

私は入力した文字列を反転するこのアセンブリコードを持っています。最大20文字まで入力できます。私の問題は、出力を見るためにEnterキーを押すと、反転文字列の最後に余分な文字があることです。
なぜ起こるのか、どのように出力から取り除くことができるのか理解してください。
文字列を表示するには関数09H int 21h、文字列を入力するには関数0Ah int 21hを使用する必要があります。私たちはTASMを使用しています。
ご協力いただき誠にありがとうございます。ありがとうございました。アセンブリ内で入力文字列を反転する

.model small 
.stack 100h 
.data 
    MSG DB "Input String(max 20 chars): ", 10, 13, "$" 
    Sentence1 DB 21,?,21 dup("$") 
    str2 dw 21 dup("$") 
.code 
start: 
    mov ax, @data 
    mov ds, ax 

    ;Getting the string input 
     mov ah,09h 
     lea dx, MSG 
     int 21h 

     lea si,Sentence1 
     mov ah,0ah 
     mov dx,si 
     int 21h 

    ;Reverse String  
     mov cl,Sentence1 
     add cl,1 
     add si,2 
    loop1: 
     inc si 
     cmp byte ptr[si],"$" 
     jne loop1 

     dec si 
     lea di,str2 
    loop2: 
     mov al,byte ptr[si] 
     mov byte ptr[di],al 
     dec si 
     inc di 
     loop loop2 

     ;Printing the reverse string  
      mov ah,09h 
      lea dx,str2 
      int 21h  

     mov ah, 4ch 
     int 21h 
end start 
+0

追加の文字は何ですか?リード文字列は最後にCR(ASCII 13)を持つことに注意してください。また、読み込み文字列の終わりを見つけるループは必要ありません。読み込まれた文字数は '[Sentence1 + 1] 'によって返されます。 – Michael

+0

余分な文字(ハートのような)、文字Pが逆向きです。それから私はループ1を削除する必要がありますか? – naomiyx

答えて

2
str2 dw 21 dup("$") 

通常、これはdbディレクティブを使用することになります。

は、ここに私のコードです。


mov cl,Sentence1 
add cl,1 

反転ループは、そのループカウンタとしてCX使用していますが、あなたはそれを正しく設定しないでください!
"Sentence1"入力構造の2番目のバイトには、CXレジスタに必要な値が入ります。終端文字を検索する必要はありません。もしあなたがしたら、あなたはむしろ '$'の代わりにASCIIコード13(改行)を探す必要があります。 SIの設定

mov cl, [si + 1] ;Number of characters in the string 
mov ch, 0   ;Make it a word because LOOP depends on CX (not just CL) 

その後、次のようになります。

add si, 2   ;To the start of the string 
add si, cx   ;To the position after the string 
dec si    ;To the last character of the string 

より短い:

add si, cx 
inc si 

これまで、ユーザーが入力テキストをしなかった場合は、お勧めします逆転を完全にバイパスしてください!これは、jcxzが次のコードで使用するものです。

lea si, Sentence1 
mov ah, 0Ah 
mov dx, si 
int 21h 

;Reverse String  
mov cl, [si + 1] 
mov ch, 0 
add si, cx 
inc si 
lea di, str2 

jcxz EmptyString  ;By-pass the reversal entirely! 

loop2: 
mov al, byte ptr[si] 
mov byte ptr[di], al 
dec si 
inc di 
loop loop2 

EmptyString: 
;Printing the reverse string (could be empty) 
mov ah, 09h 
lea dx, str2 
int 21h 
+0

OMGありがとう! ITは間違いなく正常に機能します!私はあなたが言ったことを勉強します、ありがとう! – naomiyx