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

MIPS程序实现重复行映射相同十六进制编号的问题排查请求

MIPS程序实现重复行映射相同十六进制编号的问题排查请求

各位好,我写了一段MIPS汇编代码,目的是读取input.txt文件的每一行,给每行加上递增的十六进制行号后输出。但现在遇到了问题:切换到新行的时候,行号出现了重复(或者说没有正确递增/显示),试了调整还是没解决,麻烦帮忙看看哪里出问题了?

以下是我的代码:

.data
fin: .asciiz "input.txt"

buffer: .space 1

line: .space 1024

line_counter: .word 1  # initialize line counter to 1

com: .asciiz " "

result: .space 8

.globl main

.text

main:

la $s1,buffer
la $s2,line
li $s3,0      # current line length

# open file
li $v0, 13    # syscall for open file
la $a0, fin   # input file name
li $a1, 0     # read flag
li $a2, 0     # ignore mode
syscall       # open file
move $s0, $v0 # save the file descriptor

read_loop:
# read byte from file
li $v0, 14    # syscall for read file
move $a0, $s0 # file descriptor
move $a1, $s1 # address of dest buffer
li $a2, 1     # buffer length
syscall       # read byte from file

# keep reading until bytes read <= 0
blez $v0, read_done

# naively handle exceeding line size by exiting
slti $t0, $s3, 1024
beqz $t0, read_done

# if current byte is a newline, consume line
lb $s4, ($s1)
li $t0, 10
beq $s4, $t0, consume_line

# otherwise, append byte to line
add $s5, $s3, $s2
sb $s4, ($s5)

# increment line length
addi $s3, $s3, 1

b read_loop

consume_line:
# null terminate line
add $s5, $s3, $s2
sb $zero, ($s5)

# reset bytes read
li $s3, 0

# convert line counter to hexadecimal string using itoa system call
li $v0, 34          # syscall for itoa
lw $a0, line_counter # load line counter
la $a1, result     # load address of result string
li $a2, 16         # specify base 16 (hexadecimal)
syscall            # convert line counter to hexadecimal string

# Print the hexadecimal number
li $v0, 4       # syscall for printing string
la $a0, result  # load the address of the result string
syscall

# increment line counter
lw $t0, line_counter
addi $t0, $t0, 1
sw $t0, line_counter

li $v0, 4
la $a0, com
syscall

# print line (or consume it some other way)
move $a0, $s2
li $v0, 4
syscall

# print newline
li $a0, 10
li $v0, 11
syscall

b read_loop

read_done:
# close file
li $v0, 16     # syscall for close file
move $a0, $s0  # file descriptor to close
syscall       # close file

# exit the program
li $v0, 10
syscall

我尝试过调整部分逻辑,但切换新行时的问题依然存在,希望能得到大家的指点,看看是行号递增逻辑、字符串处理还是系统调用的使用哪里出了问题?

备注:内容来源于stack exchange,提问作者MA plus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 12:54:35