You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TASM中如何移除字符串前两个字符?输入输出异常求助

解决TASM输入字符串后输出乱码的问题

问题根源

  1. DOS的0Ah中断输入缓冲区采用固定格式:[最大允许长度][实际输入长度][输入字符序列],直接用09h中断输出缓冲区首地址时,前两个控制字节会被当成字符输出,导致乱码。
  2. 代码中print函数的调用缺少参数传递:执行call input后,栈中之前push的缓冲区地址已经被弹出,后续call print时函数获取的是无效地址,会加剧输出错误。
  3. 在input函数中修改dx寄存器的操作无法在函数退出后保留,寄存器属于易失性资源,函数返回后其值不会同步到调用者上下文。

解决方案

你的input函数已经正确在输入字符串末尾添加了$结束符,这部分无需修改,只需调整输出逻辑即可,以下是两种可行方法:

方法一:直接传递正确的输出起始地址

修改main中的调用逻辑,向print传递缓冲区首地址+2(跳过前两个控制字节):

main:
  mov ax, data
  mov ds, ax

  push offset first
  call input
  call endl
  push offset first + 2  ; 指向实际输入字符的起始位置
  call print
  call endl
  
  push offset second
  call input
  call endl
  push offset second + 2  ; 指向实际输入字符的起始位置
  call print
  call endl
  

  mov ah, 4ch
  int 21h

方法二:修改print函数自动跳过控制字节

在print函数内部对传入的地址做偏移处理,跳过前两个控制字节:

print proc
  push bp
  mov bp, sp
  
  mov dx, [bp+4]
  add dx, 2  ; 跳过最大长度和实际长度两个字节
  xor ax, ax
  mov ah, 09h
  int 21h
  
  pop bp
  ret
print endp

同时修正main中的调用,确保每次call print前都传入缓冲区首地址:

main:
  mov ax, data
  mov ds, ax

  push offset first
  call input
  call endl
  push offset first
  call print
  call endl
  
  push offset second
  call input
  call endl
  push offset second
  call print
  call endl
  

  mov ah, 4ch
  int 21h

内容的提问来源于stack exchange,提问作者Nick Schemov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 20:38:25