在MIPS中存储用户输入

问题描述 投票:0回答:2

我正在尝试在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

assembly mips
2个回答
0
投票

您没有正确使用read string系统调用。我怀疑你实际上没有看过如何使用它的文档。你必须传递两个参数:

$a0 = address of input buffer
$a1 = maximum number of characters to read

所以你应该这样做:

la $a0, name
li $a1, 20

然而,这不应该导致崩溃,因为$a0应该仍然保留你为之前打印设置的firstPromptString的地址,这是有效的可写内存。


0
投票

我们的讲师建议我们首先用高级语言编写代码,然后将其转换为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 '\0'

.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 '\0')
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

希望能帮助到你:)

© www.soinside.com 2019 - 2024. All rights reserved.