简体   繁体   中英

How to get user inputted strings into an array in MIPS

I am working on a program that is going to read in strings from the user until one of the strings says "END". I need to read in each string and store it in an array so that I can access the values in another part of the program. I know that there will be no more than 20 strings read in and that each string will not exceed 15 characters.

So far, this is what I have tried:

#Arrays
animals: .word 80

la $s0, animals         #Load the address of animals array into #$s0
add $t6, $0, $s0              #Copy address of animlas into $t6

Getting User Input:

addi $v0, $0, 8         #syscall code for read user input
la $a0, animal             #Where to store read string (animal)
addi $a1, $0, 15            #Max character allowance
syscall                      #Execute

Putting the values into the array:

sw $a0, 0($t6)          #Load the address of animal into animals array
addi $t6, $t6, 4            #Increment index of array for next element

Then the read string is sent to a string compare function which I have tested thoroughly; it's working properly. The compare function tests if the read string is equal to "END". After returning from the function the code continues to loops until it reads "END"

The main point is, what is the best way to read in strings to an array in MIPS? I'm fairly new to MIPS, so any help would be greatly appreciated!

I'd have 1 big buffer of 20 * (15+1) bytes, and a separate array of pointers to the start of each string. After reading a string into a position in the big buffer, store the pointer into the pointer array, and increment the current position in the char buffer by the length (which you get as the syscall return value).

Leave room for a 0 terminator, or store the length as well.

Or instead of keeping pointers to the start of packed strings, use an array of struct { char str[16]; } string_array[20]; struct { char str[16]; } string_array[20]; . That leave unused space inside the array, instead of in a big chunk at the end of a packed buffer.

One benefit to padding to a fixed width for each string (in this case where it makes a power of 2) is that you can do a word load ( lw ) from the position you read the string into. Then you can bne $t0, $t8, top_of_loop to check all 4 bytes at once for being "END\0" and if not keep looping. (Get that 4-byte value into $t8 with lui/ori or with a load.)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM