Exit from Adding Integers Loop with a Character

2019-07-26 06:32发布

问题:

I'm trying to write the MIPS code of summing integers taken from user until user enters the character " * ".

Output will like "1 4 3 * Total: 8"

I wrote the code termination loop condition when user enters " -1 " instead of " * ". I tried writing '*' syntax instead of -1 but it doesn't give the sum. How can i exit from the loop when user enters " * " character? This was my first question and here is my working code for " -1 ".

 # $s0=Sum, $s1=Checkvalue 

         .data                    # Data memory area 
 prompt: .asciiz "Total: " 
         .text                    # Code area

 main:  
         move   $s0, $zero        # Sum is made "0"
         li     $s1, -1           # Checkvalue is made "-1"

 loop:   bne    $s0, $s0, exit    # Infinite loop is described
         li     $v0, 5            # Read integer into $v0
         syscall                  # Make the syscall read_int

         move   $t0, $v0          # Move the integer read into $t0

         beq    $t0, $s1, exit    # If the read value is equal "-1", exit
         add    $s0, $t0, $s0     # Add the read integer to sum
         j      loop              # Return loop

 exit:
         li     $v0, 4            # Syscall to print string
         la     $a0, prompt
         syscall

         move   $a0, $s0          # Syscall to print string
         li     $v0, 1
         syscall

         li     $v0, 10           # Syscall to exit
         syscall

 # Reference: www.es.ele.tue.nl/~heco/courses/ProcDesign/SPIM.ppt

My second question is that I used "syscall", is my usage suitable for stdin and stdout, system functions?

Thank you so much.

回答1:

You are reading integers like -1, and it's clear * is not an integer. To exit the loop, you will have to figure out how to read characters and integers. If your numbers are only one digit long, you can read all input as characters and convert to integers as necessary. Otherwise, you will have to read in strings and convert to integers.

As for your second question, you are correct in using syscall for standard input and output system functions.