2015-10-17 32 views
0

我是新來的mips,我如何比較預定義的字符串與用戶輸入?MIPS彙編語言比較預定義的字符串與用戶輸入

下面是我的代碼,要求用戶繼續或不是(Y/N)。如果Y然後跳回去開始,否則到最後。最後,$t110010000,$t210010046如果我輸入Y

問題在哪裏?

.data 

# Create some null terminated strings which are to be used in the program 
buffer:   .space 10 
strAgain:  .asciiz "Continue (Y/N)? " 
strY:   .asciiz "Y\n" 
strN:   .asciiz "N" 

.text 
.globl main 

main: 

    ... 

    li $v0, 4     
    la $a0, strAgain   
    syscall      

    li $v0, 8     
    la $a0, buffer 
    li $a1, 10     
    syscall      
    move $t1, $a0    

    la $t2, strY    
    bne $t1, $t2, end 
    j main 

end: 
    li $v0,10  # Exit 
    syscall   

回答

0

您試圖通過比較地址來比較字符串,這是一種有缺陷的方法。

你寫什麼就相當於下面的C代碼:

char *strY = "Y\n"; 
char buffer[10]; 

int main() { 
    for (;;) { 
     printf("Continue (Y/N)? "); 
     scanf("%s", buffer); 
     if (buffer != strY) 
      break; 
    } 
    exit(); 
} 

希望很明顯,在C代碼中的錯誤是,你應該使用strcmp比較字符串,不檢查指針平等。

所以,你需要寫strcmp功能MIPS裝配:

int 
strcmp(const char *s1, const char *s2) 
{ 
    for (; *s1 == *s2; s1++, s2++) 
     if (*s1 == '\0') 
      return 0; 
    return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1); 
}