它如何知道字符串何时结束而没有终止符呢?(代码如下) [英] How does it know when string ends without a terminator? (Code below)

查看:33
本文介绍了它如何知道字符串何时结束而没有终止符呢?(代码如下)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习火星上的MIPS,根据以下代码,我感到困惑。因为当我将输入的字符串加载到保留空间时,即使没有终止符,代码也能正常输出。这是为什么呢? 我认为每个字符串都需要一个终止符,以便输入缓冲区知道何时停止。 有没有一张是自动填的还是.?提前谢谢您。 代码为:

# Filename: mips3.asm
# Author: me
# Program to read a string from a user, and
# print that string back to the console.
.data
prompt:     .asciiz "Please enter a string: "
output:     .asciiz "
You typed the string: "
input:      .space 81       # Reserve 81 bytes in Data segment
inputSize:  .word 80        # Store value as 32 bit word on word boundary
                        # A word boundary is a 4 byte space on the
                        # input buffer's I/O bus.
# Word:
    # A Word is the number of bits that can be transferred
    # at one time on the data bus, and stored in a register
    # in mips a word is 32 bits, that is, 4 bytes.
    # Words are aways stored in consecutive bytes,
    # starting with an address that is divisible by 4

.text
# Input a string.
li $v0, 4
la $a0, prompt
syscall

# Read the string.
li $v0, 8           # Takes two arguments
la $a0, input       # arg1: Address of input buffer
lw $a1, inputSize   # arg2: Maximum number of characters to read
syscall

# Output the text
li $v0, 4
la $a0, output
syscall

# Print string
li $v0, 4
la $a0, input
syscall

# Exit program
li $v0, 10
syscall

推荐答案

系统调用的MARS文档:

..。服务8-遵循UNIXfgets的语义。对于指定的长度n,用户输入的字符串不能超过n-1。如果输入的字符串小于这个长度,则此系统调用会在末尾添加换行符。在任何一种情况下,此系统调用都使用空字节填充。.

因此,在您的情况下,任何78字节或更少的输入字符串都会同时获得换行符和空终止符。


换行符很麻烦,因为我们通常不想要它。

另外,.space 81在程序加载时将为零,因此在第一次syscall之后,您将看到末尾填充了零,但第二次syscall不一定(即,如果输入较短),因此syscall#8的NULL终止行为是有用和必要的-特别是因为服务不返回输入的长度!


还要注意,MARS在菜单项中提供了文档:

"帮助"菜单"↪mips"选项卡"→系统调用"子选项卡

"帮助"菜单上还有一些其他有趣的材料/信息。

这篇关于它如何知道字符串何时结束而没有终止符呢?(代码如下)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆