x8086汇编字符颜色修改异常:元音重复输出问题求助
问题排查:汇编代码元音字符重复输出3-5次
运行代码后发现元音字符会被重复输出3到5次,多次测试输出结果均存在该问题。本人认为代码逻辑无误,但实际运行结果不符合预期,恳请排查问题原因。
待排查代码
org 100h .data sentence db 100 dup(?),0dh ;sentence with size 100 and an 'enter' to end it vowels db 'aeiouAEIOU' ; vowels colors db 04h, 0Bh, 0Dh, 0Ah, 0Eh ; red cyan pink green yellow ; add your code here .code mov ax,@data mov ds,ax ; reading the input untill the user enters 'enter' ; or untill it reachs 100 character mov cx,100 mov si,0 mov ah,1 input: int 21h cmp al,0dh jz endOfLine mov sentence[si],al inc si loop input jmp L1 ; when the user inputs 'enter' ; it makes the next character of the sentence a 'enter' ; to make it as end of line refference endOfLine: mov sentence[si],0dh ; to centralize the output L1: mov dh, 12 mov dl, 30 mov bh, 0 mov ah, 2 int 10h ; output part mov si,0 output: mov dl,sentence[si] cmp dl,0dh jz stop_print ;checks for uppercase and lowercase vowel mov cx,5 mov di,0 check_if_vowel: mov bl,vowels[di] cmp dl,bl jz is_vowel mov bl,vowels[di+5] cmp dl,bl jz is_vowel inc di loop check_if_vowel mov ah,2 int 21h inc si jmp output is_vowel: mov al,bl mov ah,09h mov bl,colors[di] int 10h mov ah,2 mov dl,al int 21h mov ah,09h mov bh,0 mov bl,0Fh int 10h inc si jmp output stop_print: ret
问题原因分析
核心问题出在int 10h的09h功能调用上:
ah=09h的int 10h指令作用是在当前光标位置,以指定属性输出CX次字符,但代码中没有为该功能设置CX的值。- 进入
is_vowel标签时,CX寄存器的值是check_if_vowel循环剩余的次数(比如第一次匹配到元音时CX=5,第二次匹配时CX=4,以此类推),这就导致int 10h会重复输出CX次当前字符,最终表现为元音重复3-5次。
修复方案
在每次调用ah=09h的int 10h之前,将CX设置为1,确保只输出一次字符:
is_vowel: mov al,bl mov ah,09h mov bl,colors[di] mov cx,1 ; 设置输出次数为1 int 10h mov ah,2 mov dl,al int 21h mov ah,09h mov bh,0 mov bl,0Fh mov cx,1 ; 设置输出次数为1 int 10h inc si jmp output
额外优化建议
可以将设置CX=1的操作放在is_vowel开头,避免重复代码:
is_vowel: mov cx,1 ; 统一设置输出次数为1 mov al,bl mov ah,09h mov bl,colors[di] int 10h mov ah,2 mov dl,al int 21h mov ah,09h mov bh,0 mov bl,0Fh int 10h inc si jmp output
内容的提问来源于stack exchange,提问作者Bmox
相关产品推荐
相关产品推荐

