bI'm not so sure why it's not reading the input and deciding to repeat or end.. Here is my code, help would be appreciated!

.data  
again:
    .asciiz "Again (y or n)? "  
answer:
    .asciiz " "  

.text  
.globl main  
  main:
    li  $v0, 4  
    la  $a0, again  
    syscall  

    la  $s4, answer
    jal get 

    beq $v0, 'y', main
    beq $v0, 'Y', main

    li  $v0, 10 
    syscall 

  get:  
    li  $v0, 12  
    li      $a1, 2  
    syscall  
    jr  $ra
有帮助吗?

解决方案

Consider this:

.data
again:
    .asciiz "Again (y or n)? "  
answer:
    .space 256

.text  
.globl main  
  main:
    li  $v0, 4  
    la  $a0, again  
    syscall  

    la  $a0, answer
    li  $a1, 3
    li  $v0, 8
    syscall

    lb  $t4, 0($a0)

    beq $t4, 'y', main
    beq $t4, 'Y', main

    li  $v0, 10 
    syscall 

Firstly, in your code, you seem to misunderstand the way the syscalls work and how they ought to interact with functions (some docs here). Because your get routine basically just called a syscall, I took it out as adding a routine for something that basic is probably adding complexity rather than reducing it.

Next, the main problem of your code was a misunderstanding of the way input buffering works. In your code, you allocated exactly 2 bytes of space for answer, and then use syscalls to get no more than 2 bytes at a time. This will not work for stdin, because on most systems, stdin is line buffered, meaning that the user must press ENTER in order to flush the stream. This means that when the user types 'y', a syscall actually returns "y\n\0".

To fix this I expanded the syscall to read 3 characters and answer to store up to 256. Expanding this to be safe for any size is an excersize left to the reader.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top