问题描述:

I am writing a program using MIPs that takes an input string from the user and outputs the longest substring of consecutive identical characters. My problem seems to be that 'end' seems to be reached before the program outputs the target string. Any help is appreciated!

main:

la $a0,input_msg # Prompting input from user

li $v0,4

syscall

li $v0, 8 # Reading string and storing in memory

la $a0, input_string

li $a1, 100

syscall

li $t0, 0

la $t1, input_string # address of the first element

lb $a0, ($t1) # input_string[0] (the first character)

move $s0, $a0 # current_char=read_char();

move $s1, $a0 # previous_char = input_string[0];

move $s2, $a0 # final_char=input_string[0];

li $s3, 1 # current_num_chars=1;

li $s4, 1 # final_num_chars=1;

la $t5, new_line

loop:

addi $t0, $t0, 1 # for(k=1; k<i-1; k++) {

add $t1, $t1, $t0

lb $t3, ($t1)

beq $s5, $t3, print_final

move $s0, $t3 # current_char=input_string[k];

bne $s0, $s1, else # if(current_char == previous_char)

addi $s3, $s3, 1 # current_num_chars++;

bge $s3, $s4, increase_final # if(current_num_chars >= final_num_chars) {

move $s1, $s0

j loop # else do nothing

increase_final:

move $s2, $s0 # final_char=current_char;

move $s4, $s3 # final_num_chars=current_num_chars;

move $s1, $s0

j loop # }

else:

move $s1, $s0

j loop # else {

# current_num_chars=1;

# }

# }

print_final:

la $a0, output_msg

li $v0, 4

syscall

li $t2, 0

print_chars:

li $t2, 0 # for(k=0; k<final_num_chars; k++) {

beq $t2, $s3, end

move $a0, $s2 # print_char(final_char);

li $v0, 11

syscall

j print_chars # }

end:

li $v0, 4 # print_string("\n");

la $a0, new_line

syscall

li $v0, 10 # exit()

syscall

网友答案:

Your print_chars loop compares $t2 (which you just set to 0) to $s3 to decide whether or not to jump to end. Thus, it will always make the same comparison, and your loop will either exit the first time it is encountered, or never end.

Plus, the comment suggests that you should be comparing to $s4, not $s3.

相关阅读:
Top