【问题标题】:Printing the x char in a string (MIPS)在字符串中打印 x 字符 (MIPS)
【发布时间】:2015-09-28 09:27:46
【问题描述】:

我的程序应该执行以下操作: - 不断地从用户 (x) 那里获取一个整数, - 在字符串中的 x 位置打印字符。 -当用户输入0时程序退出。

.text           
.globl __start  
__start:
    li $s3,20 #string length

start:      li $v0,5 
    syscall
    move $s0,$a0 #integer now in $a0
    beq $s0,$zero,exit

    li $s1,0 #counter is 0
    la $s2,str #address of string now is $s2

loop:lbu $t1,0($s2) #choosing char of string
    addi $s1,1 #increment counter by 1
    addi $s2,1 #next char
    beq $s1,$s0,print  #is the char at the position we entered?
    j loop

print:      lbu $a0,0($t1) #<------------#
    li $v0,11
    syscall
    j start

exit:       li $v0,10
    syscall     



.data
str: .asciiz "abcdefghijklmnopqrst"

当我尝试运行我标记的行时,我不断收到:“PC=0x00400034 发生异常”和“数据堆栈读取中的错误地址:0x...”。

【问题讨论】:

    标签: assembly mips qtspim


    【解决方案1】:

    $t1 在您执行lbu $a0,0($t1) 的位置不包含有效地址。 $t1 中的内容是在退出 loop 循环之前从字符串中读取的最后一个字符。

    我真的不明白循环的意义何在。你说你有一个字符串和整数 X,你想打印字符串中偏移 X 处的字符。因此,只需阅读该字符即可完成:

    la $a1,string
    addu $a1,$a1,$s0   # $a1 = &str[x].  assumes x is in $s0
    lbu $a0,($a1)      # read the character
    li $v0,11
    syscall            # and print it
    

    【讨论】:

    • 虽然这看起来是正确的,但它总是打印字符'b',无论我输入什么。在我的方法中(我知道它不是最有效的)我想将该字符移动到 $a0,所以我无法打印。我尝试同时使用 sb 和 lbu,但它们似乎都不起作用。
    • 好吧,您将错误的值移动到$s0。系统调用 5 返回在 $v0 中读取的整数,而不是 $a0
    • 非常感谢!这说明了一切。
    【解决方案2】:
    .data
    String: .space 1000
    StringSize: .word  250
    Msg: .asciiz "String length is: "
    
    .text       
    .globl main 
    main:   
    lw $a1, StringSize
    la $a0, String                    # a0 points to the string
    li $v0, 8
    syscall
    
    add $t2, $a0, $zero               # t2 points to the string
    add $t1, $zero, $zero             # t1 holds the count
    addi $t3, $zero, 10
    
    LoopString: lb $t0, 0($t2)        # get a byte from string
    beq $t0, $zero,  EndLoopString    # zero means end of string
    beq $t0, $t3, Pointer             # remove newline (linefeed)
    addi $t1,$t1, 1                   # increment count
    
    Pointer:    addi $t2,$t2, 1       # move pointer one character
            j LoopString              # go round the loop again
    EndLoopString:
    
    la $a0, Msg                       # system call to print
    add, $v0, $zero, 4                # out a message
    syscall
    
    add $a0, $t1, $zero               # system call to print
    add, $v0, $zero, 1                # out the length worked out
    syscall     
    
    add, $v0, $zero, 10
    syscall                           # good byeee :) ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多