Write a subroutine that reads a string from the user Paramet

Write a subroutine that reads a string from

the user.

Parameters ($a0, $a1):

$a0 should specify the buffer that string is

placed

$a1 register should specify the maximum

characters of input string from the user

Return value($v0):

Subroutine should save the length of the

string in $v0 register.

Subroutine should check if the string is empty.

If it is empty, $v0 should be -1.

Solution

.data
    message: .asciiz \"Please input a string:\"
    buffer:    .space 100
    stringmax: .word 100

    .text
    lw $a0, buffer
    lw $a1, stringmax

    #Call getString function
    jal getString

    move $t0, $v0
    addi $t0, $t0, -1

    j terminateProgram    

    getString:
    li $v0, 54
    move $a2, $a1
    move $a1, $a0
    la $a0, message
    syscall
    la $t1, buffer

    #check if nothing entered
    beqz $t1, $zero, emptyField      #Checks for the null character

    strlen:
    li $t2, 0    #Count initializes to 0

    loop:
    lb $t3, 0($a0)   #Next character loads into t3
    beqz $t3, exit   #Checks for the null character
    addi $a0, $a0, 1 #String pointer increment
    addi $t2, $t2, 1 #Count increment
    j loop           #Returns to the top of the loop

    exit:
    jr $ra

    emptyField:
    addi $v0, $zero, -1
    jr $ra

    terminateProgram:
    nop
    syscall

Write a subroutine that reads a string from the user. Parameters ($a0, $a1): $a0 should specify the buffer that string is placed $a1 register should specify the
Write a subroutine that reads a string from the user. Parameters ($a0, $a1): $a0 should specify the buffer that string is placed $a1 register should specify the

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site