在MIPS中存储用户输入
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在MIPS中存储用户输入相关的知识,希望对你有一定的参考价值。
我正在尝试在MIPS程序集中编写一个程序,它只是提示用户输入他们的名字,然后将他们的名字打印回来。到目前为止我的代码是
#Program that fulfills the requirements of COS250 lab 1
#Nick Gilbert
.data #Section that declares variables for program
firstPromptString: .asciiz "What is your name: "
secondPromptString: .asciiz "Enter width: "
thirdPromptString: .asciiz "Enter length: "
name: .space 20
firstOutString: .asciiz "Hi ______, how are you?"
secondOutString: .asciiz "The perimeter is ____"
thirdOutString: .asciiz "The area is _____"
.text #Section that declares methods for program
main:
#Printing string asking for a name
la $a0, firstPromptString #address of the string to print
li $v0, 4 #Loads system call code for printing a string into $v0 so syscall can execute it
syscall #call to print the prompt. register $v0 will have what syscall is, $a0-$a3 contain args for syscall if needed
#Prompting user for response and storing response
li $v0, 8 #System call code for reading a string
syscall
sw $v0, name
li $v0, 4 #System call code for printing a string
la $a0, ($v0) #address of the string to print
syscall
它会提示用户输入他们的名字,但只要输入一个字符,代码就会爆炸。我正在使用MARS IDE编辑和执行MIPS
答案
您没有正确使用read string
系统调用。我怀疑你实际上没有看过如何使用它的文档。你必须传递两个参数:
$a0 = address of input buffer
$a1 = maximum number of characters to read
所以你应该这样做:
la $a0, name
li $a1, 20
然而,这不应该导致崩溃,因为$a0
应该仍然保留你为之前打印设置的firstPromptString
的地址,这是有效的可写内存。
另一答案
我们的讲师建议我们首先用高级语言编写代码,然后将其转换为MIPS。
Python示例:
prompt = "Enter your name: "
hello_str = "Hello "
name = None
print(prompt)
name = input()
print(hello_str)
print(name)
MIPS汇编代码:
.data
prompt: .asciiz "Enter name: (max 60 chars)"
hello_str: .asciiz "Hello "
name: .space 61 # including ' '
.text
# Print prompt
la $a0, prompt # address of string to print
li $v0, 4
syscall
# Input name
la $a0, name # address to store string at
li $a1, 61 # maximum number of chars (including ' ')
li $v0, 8
syscall
# Print hello
la $a0, hello_str # address of string to print
li $v0, 4
syscall
# Print name
la $a0, name # address of string to print
li $v0, 4
syscall
# Exit
li $v0, 10
syscall
希望能帮助到你:)
以上是关于在MIPS中存储用户输入的主要内容,如果未能解决你的问题,请参考以下文章