Linux x86汇编 - 获取用户输入

4

希望这是一个简单的问题:

首先,我想知道有没有人知道如何在Linux上使用x86 NASM语法汇编获取用户输入。目前,我有以下代码:

section .data
    greet:       db 'Hello!', 0Ah, 'What is your name?', 0Ah  ;simple greeting
    greetL:      equ $-greet                                  ;greet length
    colorQ:      db 'What is your favorite color?'            ;color question
    colorL:      equ $-colorQ                                 ;colorQ length
    suprise1:    db 'No way '                               
    suprise1L    equ $-suprise1
    suprise3:    db ' is my favorite color, too!', 0Ah

section .bss 
    name:        resb 20                                      ;user's name
    color:       resb 15                                      ;user's color

section .text
    global _start
_start:

    greeting:
         mov eax, 4
         mov ebx, 1
         mov ecx, greet
         mov edx, greetL
         int 80                                               ;print greet

    getname:
         mov eax, 3
         mov ebx, 0
         mov ecx, name
         mov edx, 20
         int 80                                               ;get name

    askcolor:
         ;asks the user's favorite color using colorQ

    getcolor: 
         mov eax, 3
         mov ebx, 0
         mov ecx, name
         mov edx, 20
         int 80

    thesuprise:
         mov eax, 4
         mov ebx, 1
         mov ecx, suprise1
         mov edx, suprise1L
         int 80 

         mov eax, 4
         mov ebx, 1
         mov ecx, name
         mov edx, 20
         int 80 

         ;write the color

         ;write the "suprise" 3

         mov eax, 1
         mov ebx, 0
         int 80

它的作用是询问姓名和颜色,并说:“不可能——name———color——是我最喜欢的颜色。”

我需要帮助确定用户输入的“name”和“color”变量的长度。否则,我只知道它们的最大大小是我之前声明的,就会出现一些长而丑陋的空格。

感谢您提供的任何帮助。


int 80int 0x50。你需要的是 int 0x80。 (可能是这个问题的规范重复:在执行时,汇编器sysTime出现错误) - Peter Cordes
3个回答

2

读取系统调用会在eax寄存器中返回读取的字节数。如果这个数字小于0,则说明发生了某种读取错误。


我尝试在读取指令后使用寄存器eax中的“returned”值,但这只会返回我最初声明的缓冲区大小。 - nmagerko

1

我知道这篇文章有些旧了,但是对于未来的任何人来说,还有另一种方法可以完成OP所要求的内容,只需要一行代码。虽然可能不是理想的解决方案,但对于像这样的问题,它应该能很好地工作。基本上,我们不需要尝试弄清用户输入的单词长度,而是假设他们会输入类似于“RED”或“ORANGE”等没有花哨颜色的东西。因此,让我们假设最长的颜色为8个字符。也就是说,我们可以这样做。

.bss 
     color:     resb     8

再次强调,这并不是最理想的方法,但它确实有效,在这种情况下,多几个字节不应该对其产生太大影响。


1
你将会在循环中调用读取函数。
最简单的方法,虽然不是最好的,就是逐字节读取并查找LF(10进制)字符。

请详细说明。我知道如何读取用户输入,但如果我不知道它的长度,我该如何逐字节存储输入?另外,如果没有某种字符串转整数的方法,我该如何将第10个字节与字符进行比较? - nmagerko
字节是非常短的整数。 - Joshua
我通常声明一个长度为80的缓冲区,并在用户超出它时进行投诉。 - Joshua
逐个读取字符需要禁用规范化(缓冲字符直到按下回车键)。当然这是可行的,但并不容易。 - Fabel
等等,什么?这相当于在用户空间中循环调用getc(stdin)而不进行缓冲。 - Joshua

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接