Amin
Amin

Reputation: 38

Taking string in 8086 Assembly and counting a characters in it

I'm currently trying to write a code in assembly for taking some string from user and calculate the 'a' characters in it. The job seems very simple but the problem is I can't really count properly and don't know what is the problem. For example for the word 'amin', the output is 97, or for others something like >6. And there is not many tutorials in internet for assembly 8086. So if anyone can help I'll be thankful.

stk     segment
    dw 32 dup(?)
stk     ends

dts     segment
    p1 db 10,13,'Please enter max 80 char',10,13,'$'
    p2 db 10,13,'Number of (a) chars:  $'
    max db 80
    len db ?
    count db 0
    char db 'a'
    str db 80 dup (?)
dts ends

cds     segment
    assume cs:cds, ss:stk, ds:dts
    main proc far
        mov ax, seg dts
        mov ds,ax
        mov ah,09
        mov dx,offset p1
        int 21h

        mov ah,0ah
        mov dx,offset max
        int 21h

        lea si,str
        mov cl,len
        mov ch,0 ; Initializing CX(Counter) Register for loop
check:
        mov al,[si]
        cmp char,al
        jne skip
        inc count
skip:
        inc si; Next char in str
        loop check

        mov al,count
        mov ah,0
        mov dl,10
        div dl
        add ax,3030h; making the right ascii code for printing
        mov bx,offset max-3
        mov [bx],ax
        mov ah,09
        mov dx,offset p2
        int 21h

        mov ah,4ch
        int 21h

    main endp
cds ends

    end main

Upvotes: 1

Views: 4915

Answers (1)

prl
prl

Reputation: 12435

int 21h,ah=0ah reads user input into the buffer at DS:DX. The first byte of the buffer pointed to by DS:DX is the maximum length, followed by the actual length, followed by the characters read. You need to define str immediately following len; otherwise the input overwrites count and char. The reason you get 97 is that count is overwritten by the first character of your input.

To make this clearer in your code, I suggest writing it like this:

buf:
    max db 80
    len db ?
    str db 80 dup (?)

count db 0
char db 'a'

Then before the int 21h,ah=0ah,

    mov dx, offset buf

Upvotes: 2

Related Questions