2012-04-29 163 views
0

我有一个程序,它需要一个整数作为来自用户的输入(使用系统调用5)。当用户输入特殊字符时! @#$%^ _ - ?)(而不是崩溃的整数,我怎么能解决方案,而不是显示崩溃它的错误消息Mips汇编语言错误检查

这是我写

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 -- 
+0

也许有更好的方法去做你想做的事情。你能澄清吗? – blackcompe

+0

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

+0

样本输出: –

回答

0

不能从崩溃停止它总是尝试解析输入的整数,您可以显示错误消息,并使用异常处理程序恢复

MARS exception handling

更新:

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

到写处理程序的替代方法是用read_charread_string和自己进行萃取读取用户输入到缓冲区中。使用read_char需要您接受最多一个新行的字符。

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

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

+0

是的,但我不知道如何编写一个异常处理程序,而我的教科书并没有很好地覆盖这个部分。我很感激,如果你能给我一个关于如何去做的简单想法,或者甚至将我引荐到一些有例外的文档的网站。 –

+0

@DaffyDaffy:你看我的答案中的链接? – blackcompe

+0

ooops对不起,完全看了一下,谢谢你会检查出来! –