我有一個將字符串轉換爲整數的程序。只要用戶輸入有效的數字,程序就可以正常工作。但是,一旦我添加了一些錯誤檢查,以確保輸入的值實際上是數字,我遇到了一些困難。最初,我將tryAgain標記作爲getData過程中的第一行代碼。但是,錯誤檢查意味着在下一次迭代期間輸入有效數字後,無效輸入後,程序不斷返回消息「無效輸入」。將tryAgain標籤放在第一行代碼中會導致程序繼續返回無效輸入消息,即使有效輸入出現無效輸入時也是如此。首先,我試圖將tryAgain標籤放在當前位置,但我認爲它正在無限循環中運行。其次,如果程序跳轉到invalidInput,我試圖重置變量,但是這並沒有解決它(我嘗試了tryAgain的原始位置和當前位置)。MASM將字符串轉換爲整數:處理無效輸入
這是用於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
只要你有地方我感與此一起去,這是我的僞代碼:
由10
分割的每個字符斷絃和48D相減得到的整數開始在字符串
乘答案的價值的開始。防爆。學生輸入156. 49被存儲爲變量temp中的第一個字符。從49減去48.整數是1.
將整數加到答案的值。
Inc esi(向右移動一個字符)。
Loop。
非常好!有時候是簡單的事情....謝謝! – user1852050