使用 printf asm nasm 在一行上打印整个数组 [英] Printing an entire array on a single line using printf asm nasm
问题描述
我正在使用 NASM 来编译我的 ASM 程序,但我无法弄清楚如何使用循环在一行上打印整个数组(不一定知道数组有多大).每当我用 printf 创建一个循环时,它都会在多行而不是一行上打印值.知道如何使 printf 使用循环在一行上打印数组的多个值吗?我得到值 1-9 但都在不同的行而不是同一行.这是在不使用除 printf c 库之外的外部库的情况下完成的.非常感激任何的帮助.我的代码如下.
I am using NASM for compiling my ASM program and I am having trouble figuring out how to print an entire array on a single line (without necessarily knowing how big the array is) using a loop. Whenever I create a loop with printf it prints the values on multiple lines instead of one line. Any idea how to make printf print multiple values of an array on a single line using a loop? I get values 1-9 but all on a different line instead of the same line. This is to be done without using external libraries other than: the printf c library. Any help would be most appreciated. The code I have is below.
extern printf
SECTION .data ; Data section, initialized variables
array: dd 1, 2, 3, 4, 5, 6, 7, 8, 9, 0; this is a test array for testing purposes
arrayLen: dd 9 ; length of array
aoutput: db "%d", 10, 0 ; output format
SECTION .text ; Code section.
global main ; the standard gcc entry point
main: ; the program label for the entry point
push ebp ; set up stack frame
mov ebp,esp
mov ecx, [arrayLen] ; loop counter set up
mov esi, 0 ; counter to increment set up for looping through array
.loop:
push ecx ; make sure to put ecx (counter) on stack so we don't lose it when calling printf)
push dword [array + esi] ; put the value of the array at this (esi) index on the stack to be used by printf
push dword aoutput ; put the array output format on the stack for printf to use
call printf ; call the printf command
add esp, 8 ; add 4 bytes * 2
pop ecx ; get ecx back
add esi, 4
loop .loop
mov esp, ebp ; takedown stack frame
pop ebp ; same as "leave" op
mov eax,0 ; normal, no error, return value
ret ; return
推荐答案
唯一决定某事是打印在单行还是多行的,是打印换行符 (\n
) 与否.
The only thing that determines whether something is printed on a single line or multiple, is if you print a newline character (\n
) or not.
这里,当您说 10
时,它是换行符的 ASCII 值.如果你改变这个:
Here, when you say 10
, that is the ASCII value for a Line Feed. If you change this:
aoutput: db "%d", 10, 0
为此:
aoutput: db "%d ", 0
您的值将由空格分隔,而不是由换行符分隔.
your values will be separated by spaces, instead of by new lines.
在序列中的最后一个值之后,可以打印一个单独的换行符:
After the final value in the sequence, you can print a lone newline character:
push 0x0A ; New line character
call putchar
这篇关于使用 printf asm nasm 在一行上打印整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!