【问题标题】:How to remove newline in MIPS?如何删除 MIPS 中的换行符?
【发布时间】:2012-11-29 17:07:30
【问题描述】:

所以我正忙着编写一个 MIPS 程序,它将接受一个输入字符串,然后打印该字符串的所有可能的 UNIQUE 排列。 (AKA 如果单词是 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

唯一不包含“\n”的情况是输入的字母数正好是 20 个。有什么建议吗??

修复:

这行得通:

    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:

【问题讨论】:

    标签: assembly newline mips


    【解决方案1】:

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

    # your code to prompt the user        
    
        xor $a2, $a2, $a2
    loop:
        lbu $a3, word($a2)  
        addiu $a2, $a2, 1
        bnez $a3, loop       # Search the NULL char code
        beq $a1, $a2, skip   # Check whether the buffer was fully loaded
        subiu $a2, $a2, 2    # Otherwise 'remove' the last character
        sb $0, word($a2)     # and put a NULL instead
    skip:
    
    # your code continues here
    

    另外请注意,您没有为单词保留足够的空间。您应该保留 21 个字节与

    word: .space(21)
    

    【讨论】:

    • 不太好用。 xor $a2,$a2,$a2 的目的是什么?
    • @user1739675:它将寄存器 $a2 设置为零。你有没有把 sn-p 放在提示单词的系统调用和说 la $a0,newLine 的行之间?而且,你是否激活了延迟分支?如果是这种情况,您可以在bnez $a3, loop 之后添加nop
    • 我不能发布我自己的答案,lawl。但是以您的代码为指导,我能够使用以下代码实现预期的结果。
    • @user1739675:太好了。请注意,您发布的代码与我的基本相同,因此无需修改即可使用;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 2012-06-20
    • 2017-04-02
    相关资源
    最近更新 更多