I am new to mips, how do I compare a predefined string with user input?
Below is my code asking user to continue or not (Y/N)
. If Y
then jump back to start, else go to the end. At the end, $t1
is 10010000
, $t2
is 10010046
if I enter Y
.
Where is the problem?
.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
You are attempting to compare strings by comparing addresses, which is a flawed approach.
What you have written is equivalent to the following C code:
char *strY = "Y\n";
char buffer[10];
int main() {
for (;;) {
printf("Continue (Y/N)? ");
scanf("%s", buffer);
if (buffer != strY)
break;
}
exit();
}
Hopefully it's clear that the error in the C code is that you should be using strcmp
to compare strings, not checking for pointer equality.
So, you need to write the strcmp
function in MIPS
assembly:
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.