如何在MIPS中移除换行符?

4

我正在忙于编写一个MIPS程序,它将接收一个输入字符串,并打印出该字符串的所有可能唯一的排列组合。(即如果单词是LoOp,则LoOp和LOop是相同的)。

为了实现这个目标,我知道我需要确保我的输入字符串末尾没有换行符,但我不知道如何做到这一点。以下是我目前的代码:

.data


newLine:
    .asciiz "\n"
promptUser:
    .asciiz "Enter a 20 letter or less word:\n"
word:
    .space 21

.text

main:

    la $a0, promptUser
    li $v0, 4       # Ask User for Input
    syscall

    la $a0, word
    li $a1,21       # Max number of characters 20
    li $v0,8
    syscall         # Prompting User

    la $a0,newLine      # Newline   
    li $v0, 4
    syscall

    la $a0, word        # Printing Word
    li $v0, 4
    syscall

当输入的字母数恰好为20个时,'\n'不会包含在内。有什么建议吗?

修复:

这样可以解决问题:

    li $s0,0        # Set index to 0
remove:
    lb $a3,word($s0)    # Load character at index
    addi $s0,$s0,1      # Increment index
    bnez $a3,remove     # Loop until the end of string is reached
    beq $a1,$s0,skip    # Do not remove \n when string = maxlength
    subiu $s0,$s0,2     # If above not true, Backtrack index to '\n'
    sb $0, word($s0)    # Add the terminating character in its place
skip:
1个回答

1

您可以在从系统调用8返回时解析字符串以删除该字符:

# your code to prompt the user        

    addu  $a2, $zero, $zero     # i = 0
loop:
    lbu $a3, word($a2)          # word[i]
    addiu $a2, $a2, 1
    bnez $a3, loop       # Search the NUL char code

    beq $a1, $a2, skip   # Check whether the buffer was fully loaded
                         # Otherwise 'remove' the last character
    sb $0, word-2($a2)   # and put a terminating NUL instead
skip:

# your code continues here

请注意,您没有为该单词预留足够的空间。您应该预留21个字节。
word: .space(21)

没有完全起作用。xor $a2,$a2,$a2的目的是什么? - ErikAGriffin
@user1739675:它将寄存器$a2设置为零。你是否将代码片段放置在提示单词的系统调用和说“la $a0,newLine”的行之间?另外,你是否启用了延迟分支?如果是这种情况,你可以在“bnez $a3, loop”后添加一个“nop”。 - gusbro
我不能发布自己的答案,哈哈。但是使用你的代码作为指南,我能够用以下代码实现预期的结果。 - ErikAGriffin
@user1739675:太好了。请注意,您发布的代码基本上与我的相同,因此不需要修改就应该可以正常工作 ;) - gusbro
在MIPS中不要使用xor-zero,只有x86可以这样做,特别是如果你要从一个不是$zero的寄存器中读取。在MIPS中,需要依赖于输入来进行内存依赖顺序(与std::memory_order_consume所暴露的相同)。 - Peter Cordes
另外,MIPS寻址模式具有16位立即数;您已经使用了它来表示“word”的绝对地址,因此您不需要subiu(它实际上不是真正的机器指令,只是带有负数的addiu)。sb $zero, word-2($a2)。或者更好的方法是进行指针增量,这样即使word不在低地址空间或高32KiB中,它也可以在没有伪指令的情况下运行。 - Peter Cordes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接