2

我有一个将字符串转换为整数的程序。只要用户输入有效数字,该程序就会运行良好。但是,一旦我添加了一些错误检查以确保输入的值实际上是数字,我就遇到了一些问题。最初,我将 tryAgain 标记作为 getData 过程中的第一行代码。但是,错误检查意味着在下一次迭代期间输入有效数字时,在输入无效输入后,程序会不断返回消息“无效输入”。将 tryAgain 标记放在代码的第一行会导致程序继续返回无效输入消息,即使有效输入跟随无效输入也是如此。首先,我尝试将 tryAgain 标记放在其当前位置,但我认为它正在无限循环中运行。第二,

这是 x86 处理器的 MASM。提前感谢您的建议。

这是代码:

.data
result  DWORD   ?
temp        BYTE        21 DUP(0)
answer  DWORD   ?

.code
main    PROC

(一些初步程序调用)

push OFFSET temp        ;ebp+16
push OFFSET answer      ;ebp+12
push answerSize     ;ebp+8
call    getData

(更多过程调用)

exit        ; exit to operating system
main ENDP


;*************************************************
; prompts / gets the user’s answer.
; receives: the OFFSET of answer and temp and value of answerSize
; returns: none
; preconditions: none
; registers changed:  eax, ebx, ecx, edx, ebp, esi, esp
;*************************************************
getData PROC
push        ebp
mov     ebp,esp

tryAgain:
mWriteStr   prompt_1
mov     edx, [ebp+16]       ;move OFFSET of temp to receive string of integers
mov     ecx, 12
call        ReadString
cmp     eax, 10
jg      invalidInput

mov     ecx, eax        ;loop for each char in string
mov     esi,[ebp+16]    ;point at char in string

pushad
loopString:             ;loop looks at each char in string
    mov     ebx,[ebp+12]
    mov     eax,[ebx]   ;move address of answer into eax
    mov     ebx,10d     
    mul     ebx         ;multiply answer by 10
    mov     ebx,[ebp+12]    ;move address of answer into ebx
    mov     [ebx],eax       ;add product to answer
    mov     al,[esi]        ;move value of char into al register
    inc     esi         ;point to next char
    sub     al,48d      ;subtract 48 from ASCII value of char to get integer  

    cmp     al,0            ;error checking to ensure values are digits 0-9
    jl      invalidInput
    cmp     al,9
    jg      invalidInput

    mov     ebx,[ebp+12]    ;move address of answer into ebx
    add     [ebx],al        ;add int to value in answer

    loop        loopString  
popad
jmp     moveOn
invalidInput:               ;reset registers and variables to 0
    mov     al,0
    mov     eax,0
    mov     ebx,[ebp+12]
    mov     [ebx],eax
    mov     ebx,[ebp+16]
    mov     [ebx],eax       
    mWriteStr   error
    jmp     tryAgain
moveOn:
    pop     ebp
    ret     12
getData ENDP

只是为了让您了解我的目标,这是我的伪代码:

  1. 从字符串的开头开始

  2. 将答案的值乘以 10。

  3. 从字符串中拆分每个字符并减去 48d 以获得整数。前任。学生输入 156。49 存储为变量 temp 中的第一个字符。从 49 中减去 48。整数为 1。

  4. 将整数添加到答案的值。

  5. Inc esi(向右移动一个字符)。

  6. 环形。

4

1 回答 1

1

摆脱pushadand popad。每次输入无效字符时,它都会跳回 tryAgain,然后pushad执行另一个 - 每次您跳回 tryAgain。

如果您需要保存任何寄存器,请在序言中进行并在结尾处恢复它们。

于 2012-12-02T04:03:54.887 回答