如何使用循环来获取用户输入?

时间:2016-03-27 03:57:48

标签: linux assembly x86 nasm

目的是让用户输入随机数量的数字并在屏幕上显示这些数字。例如:

input: 12 34 45 12 3
output: 12 34 45 12 3
input: 2 4 100
output: 2 4 100

这是我的代码:

section .text
GLOBAL main
EXTERN printf

section .data
integer: times 4 db 0     ;store the current data
num: times 4 db 0         ;store the current input character
count: times 4 db 0       ;count how many numbers
formatin: db "%d", 0      ; output format

main:
  push ebp
  mov ebp, esp                ;reserve the previous reg

  mov dword[integer], 1       ;set integer to 1
  mov dword[count], 0         ;set count to 0
read:
  mov eax, 3
  mov ebx, 0
  mov ecx, num
  mov edx, 1
  int 80h                     ; read in a character

  cmp dword[num], 0Dh         ; if it' s an enter
  je done
  cmp dword[num], 20h         ; if it;s a space
  je nextNum

  sub dword[num], 30h         ;replace integer to 10*integer+num
  mov eax, dword[integer]
  imul eax, 10
  add eax, dword[num]
  mov dword[integer], eax
  loop read

nextNum:                       ; push integer to stack
  add dword[count], 1
  push integer
  mov dword[integer], 1
  loop read

done:
  mov ecx, dword[count]
write:                         ; print the result
  push formatin
  call printf
  add esp, 8
loop write
  mov esp, ebp
  pop ebp
  ret

问题在于它会陷入循环中并且无法跳出它。怎么了?

代码:

cmp dword[num], 0Dh 

cmp dword[num], 20h

似乎无效。也许num存在问题?我应该把它改成一个字节吗?

由于有些人认为声明dword[num]可能会导致问题,我修复了一些代码:

section .data中的

num: times 4 db 0更改为num: times 1 db 0

所有dword[num]中的

将其更改为byte[num], 但请像以前一样保持add eax, dword[num]

但它仍然停留在循环中......

感谢@Michael Petch,我发现了一些逻辑问题,并使用以下代码替换readnextNum段:

read:
  mov eax, 3
  mov ebx, 0
  mov ecx, num
  mov edx, 1
  int 80h                           ; read in a character

  cmp byte[num], 0Ah ; if it' s an enter
  je nextNum
  cmp byte[num], 20h ; if it;s a space
  je nextNum

  sub byte[num], 30h      ;replace integer to 10*integer+num
  mov eax, dword[integer]
  imul eax, 10
  add eax, dword[num]
  mov dword[integer], eax
  loop read

nextNum:                           
  add dword[count], 1
  push dword[integer]
  mov dword[integer], 0
  cmp byte[num], 0Ah
  je done
  cmp byte[num], 20h
  je  read

但它现在会给出意想不到的答案。例如我给12 34,它打印2850,12。似乎计数或数据地址计算(我仍然无法理解)出错了

我已经弄清楚了计算的错误。实际上,虽然mov dword[integer], 0段中的nextNum将值0赋予integer,但integer实际上在第二个循环中为256,在第三个循环中为512,并且768 ......等等。任何人都可以解释为什么......

0 个答案:

没有答案