2016-12-01 50 views
-2

我被困在如何使用MASM檢查迴文。Palindrome檢查數組

#include <iostream> 
#include <cstring> 
#include<string> 
#include <algorithm> 
using namespace std; 

extern "C" 
char test(char*, int); 


int main() 
{ 
char arr[] = {NULL}; 


cout << "Enter a string: " << endl; 
cin >> arr; 



int name = strlen(arr); 
test(arr, name); 
if (name == 1) 
{ 
    cout << "It is a palindrome! " << endl; 

} 
else 
    cout << "Not a palindrome. " << endl; 

return 0; 
    } 

我問用戶一個字符串,並將其插入到一個數組。我將它發送到程序集文件,如果它爲真,它將返回'1'或者如果爲假,則返回'0'。

.686 
.model flat 

.code 


_test PROC ;named _test because C automatically prepends an underscode, it is needed to interoperate 
push ebp 
mov ebp,esp ;stack pointer to ebp 

mov eax,[ebp+8] 
mov ecx,[ebp+12] 
mov ebp,0 
mov edi,0 
mov edx,0 



loopMe: 
cmp ebp,ecx 
je True 

mov al,[eax+edi] 
mov bl,[edx+esi] 
cmp al,bl ;compare 
jne false ;if not equal then jump to false 
inc edi  
dec esi 
jmp loopMe 

True: 
mov eax,1 
jmp allDone 

False: 
mov eax,0 
jmp allDone 


allDone:  
pop ebp 
ret 
_test ENDP 

END 
當我進入它似乎總是返回0。我檢查了調試器,它會一直跳到即使值相等的假標籤的字符串

。任何幫助表示讚賞。

+2

_'cin >> arr;'_是未定義的行爲。 –

+0

爲什麼不用C++完全編寫代碼,然後使用類似[this](https://gcc.godbolt.org/)的內容來確定彙編代碼的外觀?你知道生成的程序集是正確的,因爲C++程序是正確的。然後如有必要,調整生成的彙編代碼。 – PaulMcKenzie

回答

0

所以我最終改變了一下代碼,並得到它的工作。

int main() 
{ 
char arr[32] = {NULL}; 


cout << "Enter a string: " << endl; 
cin >> arr; 



int name = strlen(arr); 
int palindrome= test(arr, name); 

if (palindrome) 
{ 
    cout << "It is a palindrome! " << endl; 

} 
else 
    cout << "Not a palindrome. " << endl; 

return 0; 
} 

然後爲ASM文件

.686 
.model flat 

.code 


_test PROC ;named _test because C automatically prepends an underscode, it is needed to interoperate 
push ebp 
mov ebp,esp ;stack pointer to ebp 

mov ebx,[ebp+8] 
mov ecx,[ebp+12] 
mov edx,ebx 
add edx,ecx 
dec edx 




loopMe: 
cmp ebx,edx 
jge True 

mov ch,[ebx] 
mov cl,[edx] 
cmp ch,cl ;compare 
jne false ;if not equal then jump to false 
inc ebx  
dec edx 
jmp loopMe 

True: 
mov eax,1 
jmp allDone 

False: 
mov eax,0 
jmp allDone 


allDone:  
pop ebp 
ret 
_test ENDP 

END 

我唯一的問題是現在,如果我輸入媽媽的媽媽,而不是它會說,它不是一個迴文。我只需要弄清楚如何在程序集中忽略個案。

+0

將所有字母字符轉換爲小寫字母。如果它們在大寫範圍內,則用'0x20'或或。 –

+0

感謝您的幫助。 –

+0

或ch,32和or cl,32是否適合我。 –