I'm trying to figure out how to use scanf
to get user input. I know to use printf
: all I have to do is push the data I want to write on the screen into the stack like this:
global _main
extern _printf
extern _scanf
section .data
msg db "Hi", 0
section .text
_main:
push ebp
mov ebp, esp
push msg
call _printf
mov esp, ebp
pop ebp
ret
But I can't figure out how to use scanf
. Can someone please just give me the simplest possible source code you can for scanf
? I really just want to put what the user types in.
I'm not used to 32bit Assembly. I've only ever used 16bit, and I know in 16bit (DOS) you can just do this:
mov ah, 3fh
mov dx, input
int 21h
input rb 100d
And whatever you type in will the placed at the address of "input."
I found this 'Programming in NASM.PDF'
; add1.asm
SECTION .data
message1: db "Enter the first number: ", 0
message2: db "Enter the second number: ", 0
formatin: db "%d", 0
formatout: db "%d", 10, 0 ; newline, nul terminator
integer1: times 4 db 0 ; 32-bits integer = 4 bytes
integer2: times 4 db 0 ;
SECTION .text
global _main
extern _scanf
extern _printf
_main:
push ebx ; save registers
push ecx
push message1
call printf
add esp, 4 ; remove parameters
push integer1 ; address of integer1 (second parameter)
push formatin ; arguments are right to left (first parameter)
call scanf
add esp, 8 ; remove parameters
push message2
call printf
add esp, 4 ; remove parameters
push integer2 ; address of integer2
push formatin ; arguments are right to left
call scanf
add esp, 8 ; remove parameters
mov ebx, dword [integer1]
mov ecx, dword [integer2]
add ebx, ecx ; add the values ; the addition
push ebx
push formatout
call printf ; call printf to display the sum
add esp, 8 ; remove parameters
pop ecx
pop ebx ; restore registers in reverse order
mov eax, 0 ; no error
ret
Which is the asm version of this C function:
#include <stdio.h>
int main(int argc, char *argv[])
{
int integer1, integer2;
printf("Enter the first number: ");
scanf("%d", &integer1);
printf("Enter the second number: ");
scanf("%d", &integer2);
printf("%d\n", integer1+integer2);
return 0;
}