user3342163
user3342163

Reputation: 303

Strlen subroutine (MIPS)

I'm trying to write a strlen subroutine in MIPS. The function works when the string is in memory, but if the string is an input from the user, the answer is always = (correct_value + 1). For example:

String: Hello
Length: 6

Why isn't it working for inputs? Here is my code. I'm using MARS.

    .data
str1:   .asciiz String: "
strTest:.space 20
str2:   .asciiz "Length: "
    .text
    .globl main

main:  
    addiu   $sp, $sp, -4            # save space
    sw      $ra, 0($sp)             # push $ra

    la      $a0, str1               # print(str1)
    li      $v0, 4
    syscall

    li      $a1, 20                 # read strTes
    la      $a0, strTest
    li      $v0, 8
    syscall


    jal     strlen                  # call strlen

    move    $t0, $v0                # save result to $t0

    la      $a0, str2               # print str2
    li      $v0, 4
    syscall

    move    $a0, $t0                # print result
    li      $v0, 1
    syscall

    lw      $ra, 0($sp)             # restore $ra
    addiu   $sp, $sp, 4             # restore $sp
    jr      $ra


strlen:
    li      $v0, 0                  # len = 0

while:  lb      $t0, ($a0)              # get char
    beqz    $t0, wh_end             # if(char == '\0') --> end while
    addi    $v0, $v0, 1             # len++
    addiu   $a0, $a0, 1             # *s++
    j       while
wh_end:
    jr      $ra

Upvotes: 1

Views: 2387

Answers (1)

Afstkla
Afstkla

Reputation: 303

My guess would be that MARS also includes the enter/return that is pressed after the user inputs his/her string. Your code looks fine, so it would be most logical that MARS returns "hello\n" instead of "hello", like you would want it to.

To solve this, you could add a check like you did for "\0", but then for "\n". I'm not sure if it will work, but you could try to add

subi $t1, $t0, 10
beqz $t1, wh_end

after beqz $t0, wh_end. This could work since the ASCII value of the \n termination character is 10, so if you subtract 10 from $t0, and end up with 0, you have a termination character.

Good luck!

Upvotes: 3

Related Questions