2016-12-01 68 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是否适合我。 –