Mips汇编语言错误检查

时间:2012-04-29 18:55:55

标签: mips

我有一个程序,它接受一个整数作为用户的输入(使用系统调用5)。当用户输入特殊字符时! @#$%^ _ - )(它不是崩溃的整数,而是如何修复程序以显示错误信息而不是崩溃?

这是我写的代码

    la $a0, prompt          # prompt the message ask for the answer n
li $v0, 4
syscall

li $v0, 5           # input the answer
syscall 

add $t1, $zero, $v0

                # store the answer in $t1

blt $t1, $s0, negative      # check for number entered < $s0
bgt $t1, $s1, exceed        # check for > $s1 number

la $a0, blank           # blank line
li $v0, 4
syscall 

示例输出:

This is a number guessing game between 0- 100. Let's begin.
Chances remains: 6
Enter your guess: 56

The secret number is higher than : 56
Chances remains: 5
Enter your guess: 67

The secret number is higher than : 67
Chances remains: 4
Enter your guess: 75

The secret number is lower than : 75
Chances remains: 3
Enter your guess: 74

The secret number is lower than : 74
Chances remains: 2
Enter your guess: 72

The secret number is lower than : 72
Chances remains: 1
Enter your guess: 70

The secret number is lower than : 70
Chances remains: 0
Sorry...You lost.
The secret number is: 69
Do you want to play again?
1.Yes 
2.No 
Choice: 2
Your average guess: 3
-- program is finished running --

1 个答案:

答案 0 :(得分:0)

你不能阻止它崩溃。它总是会尝试从输入中解析一个整数。您可以显示错误消息并使用异常处理程序进行恢复。

MARS exception handling

<强>更新

  

上面的代码实际上是数字猜谜游戏的一部分   选择一个随机数(使用系统调用42),用户输入他的   猜测。用户有6次猜测正确答案的机会。

编写处理程序的另一种方法是使用read_charread_string将用户输入读入缓冲区并自行执行提取。使用read_char要求您接受最新行的字符。

当您遍历缓冲区时,请确保每个字符的值介于48和57之间(请参阅ASCII图表)。如果该值超出范围,则显示错误。否则,从48中减去该值以获得数字,将数字乘以10的位置,并将其添加到累计总和。我建议向后迭代缓冲区,以便计算10的位置很简单。

该算法的伪代码可以在这个Casting in MIPS主题中找到。

相关问题