how to check a user input string if it is a empty string in mips

I try to write a simple MIPS program that accepts user input which is a string, then checks if the user does not input anything to quit the program. I try to use beq to compare the user's input and an empty string, but I do not know how to assign an empty string to a register.

.data userinput: .space 8 .txet loop: li $v0,8 la $a0,userinput syscall li $v0, 4 la $a1, // try to assgin an empty string to $a1 beq $a0,$a1, exit j loop exit: li $v0 10 syscall 
asked Feb 27, 2021 at 1:06 xinrui cheng xinrui cheng 1 1 1 bronze badge

1 Answer 1

  1. Because strings are a variable length data structure, they go in memory — one character after another at successive (byte) memory locations, and usually as with C, NUL character terminated. They are referenced by their starting address, aka the lowest address in the string, aka pointer to the first byte of the string.
  2. If you compare strings by their reference address, you'll know whether two strings live at the same memory location and if they do they're equal (in that case, of course, the strings hold the same value), but if they are not at the same memory location, then you've learned nothing about whether the string data is the same or not. To compare two strings, you need to compare their bytes in memory to see if they're the same.
  3. You don't need a complete, general-purpose string compare to see if a string is empty. Experiment with the string entered into memory by simply doing a return, and see what you get. That's what to look for when you want to see if the string is empty.

I believe it will have a newline followed by a nul character. I don't think any user input using syscall #8 could legitimately have any further character data after the newline, so I think for the empty input string test, it would be sufficient to look for the newline as the first character of the string.

  1. beq / bne are useful — but as I said above you need to compare character data not reference addresses. So, load the first byte of string from memory and compare it to the newline character constant value.

A truly empty string would start (and finish) with a single NUL terminating byte, and that's the character we would look for instead of looking for the newline character, but MARS syscall #8 appends the newline character (that the user types to complete the input) into the characters of input, so there's a difference then of looking for a truly empty string and looking for the minimal possible (empty) input from syscall #8.