2010-07-17 46 views
1

我有一個關於計算字符串長度的問題。 我總是得到一些像2432一樣的數字,你我傳遞一個像「abc」的字符串。關於字符串長度計數的一些問題

我認爲這個問題是在這條線

mov bl, byte [esi] 

但我不知道爲什麼。 也許這是與字符長度在位?

問題是64位操作系統還是雙核處理器? (我以某種方式懷疑,因爲我認爲第一行「位32」應該解決問題)。

PS .:這是一個練習,這就是爲什麼我需要確定像這樣的字符串的長度。

代碼:

bits 32 
extern _printf 
extern _scanf 
global _main 

section .data 
number_frmt db 10,"%d",10,0 
enter_str db "Enter some string: ", 10,0 
string_frmt db "%s", 0 

section .bss 
entered_string resb 100 

section .text 

_main: 
    pushad 

    push dword enter_str 
    call _printf 
    add esp, 4 

    push dword entered_string 
    push dword string_frmt 
    call _scanf 
    add esp, 4 ;leave the entered string in the stack 

    call count ; count it and put the result to eax 

    push dword eax 
    push dword number_frmt 
    call _printf 
    add esp, 12 

    popad 
    ret 

count: 
    push esi ;save it 
    push ebx ;save it 
    mov eax, 0 ;init eax=0 
    mov esi, [esp+12] ;put the entered string to esi 

.loop: 
    mov bl, byte [esi] ;get the first char 
    inc eax    ;eax++ 
    add esi,1   ;point to next char 
    cmp bl,10   ;is it new line? 
    jne .loop   ;if not loop 
    dec eax    ;eax-- (because of newline at the end) 
    pop ebx    ;retrieve ebx 
    pop esi    ;retrieve esi 
    ret 

回答

4
cmp bl,10   ;is it new line? 

應該

cmp bl,0 

,因爲C/C++字符串每次結束由0 /終止,所以你其實已經尋找一個隨機位置在下一個10的記憶中。

1

使用scanf可能不是一件好事,因爲它會混淆事項,切換獲取,新行也是有效字符,應該算作您的計數的一部分。字符串NUL終止(自動)

count: 
    push esi ;save it 
    push ebx ;save it 
    xor eax, eax; initialize it to zero 
    mov esi, [esp+12] ;put the entered string to esi 

.loop: 
    mov bl, byte [esi] ;get the first char 

    cmp bl, bl   ;set the flags 
    jz .out   ;nul character 

    inc eax 
    jmp .loop 

    pop ebx    ;retrieve ebx 
    pop esi    ;retrieve esi 

    ret