0
votes

I am trying to write a program that gets a user string input and reverse that string in MIPS. However, I must be doing something horribly wrong as it doesn't just display the user input in reverse but, it also reverses the prompt to the user. It seems that the user input is not identified with a null(zero?) character in the end.

.data
prompt: .asciiz "Please enter your name. You're only permitted 20 characters. \n"
userInput: .space 20 #user is permitted to enter 20 characters

.globl main
.text
main:
    # user prompt
    li $v0, 4
    la $a0, prompt
    syscall

    # getting the name of the user
    li $v0, 8
    la $a0, userInput
    li $a1, 20
    syscall 

    add $t0, $a0, $0            # loading t0 with address of array
    strLength: 
        lbu   $t2, 0($t0)
        beq   $t2, $zero, Exit  # if reach the end of array, Exit
        addiu $t0, $t0,   1     # add 1 to count the length
        j strLength
    Exit:

    add $t1, $t0, $0      # t1 = string length
    li  $t2, 0            # counter i = 0

    li $v0, 11
    reverseString:
        slt  $t3, $t2, $t1    # if i < stringlength
        beq  $t3, $0,  Exit2  # if t3 reaches he end of the array
        addi $t0, $t0, -1     # decrement the array 
        lbu  $a0, 0($t0)      # load the array from the end
        syscall
        j reverseString
    Exit2:

    li $v0, 10
    syscall
1

1 Answers

1
votes

Problem number 1:

add $t1, $t0, $0      #t1 = string length

What you're assigning to $t1 here isn't the length of the string; it's the address of the first byte past the end of the string.

Problem number 2 is that you never increment $t2 (or decrement $t1) within the reverseString loop.

I suggest that you make use of the debugging features in SPIM/MARS (like the ability to set breakpoints and single-step through the code), as that would've made finding these problems yourself fairly simple.