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

MIPS汇编字符串比较函数异常:输入匹配仍输出字符串不相等

MIPS字符串比较异常问题解决方案

问题根因

MIPS架构下使用syscall 8读取用户字符串时,会将输入末尾的回车换行符(ASCII码0xA)也写入目标缓冲区,不会自动移除:

  • 预定义的simbolo1存储内容为连续字节:s a s s o \0
  • 用户输入sasso后按下回车,缓冲区实际存储内容为:s a s s o \n \0

逐字节对比时到第6位,换行符和\0不相等,因此会触发不相等的判定逻辑。

修复方案

推荐在读取字符串完成后,主动将末尾的换行符替换为字符串终止符\0,修改getstr函数如下:

# getstr -- prompt and read string from user
#
# arguments:
#   t2 -- address of string buffer
getstr:
    # prompt the user
    la      $a0,prompt
    li      $v0,4
    syscall

    # read in the string
    move    $a0,$t2
    li      $a1,79
    li      $v0,8
    syscall

    # ----- 新增代码:移除末尾换行符 -----
    move    $t0, $a0          # 保存缓冲区首地址到t0
trim_loop:
    lb      $t1, ($t0)
    beq     $t1, $zero, trim_end  # 已经到字符串结尾,直接退出
    bne     $t1, 0xA, trim_next   # 不是换行符,遍历下一个字符
    sb      $zero, ($t0)          # 换行符替换为\0
    j       trim_end
trim_next:
    addi    $t0, $t0, 1
    j       trim_loop
trim_end:
    # ----- 新增代码结束 -----

    # should we stop?
    la      $a0,dot                     # get address of dot string
    lb      $a0,($a0)                   # get the dot value
    lb      $t2,($t2)                   # get first char of user string
    beq     $t2,$a0,exit                # equal? yes, exit program

    jr      $ra                         # return

修改完成后再次测试,输入完全匹配的字符串即可正确输出相等提示。

内容的提问来源于stack exchange,提问作者Tommaso Masaracchio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:57:02