[英]Printing an entire array on a single line using printf asm nasm
我正在使用NASM来编译我的ASM程序,但是我很难弄清楚如何使用循环在一行上打印整个阵列(不必知道该阵列有多大)。 每当我用printf创建一个循环时,它都会在多行而不是一行上打印值。 任何想法如何使printf使用循环在一行上打印数组的多个值? 我得到的值是1-9,但都在不同的行而不是同一行。 无需使用除printf c库以外的外部库即可完成此操作。 非常感激任何的帮助。 我的代码如下。
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
)。
在这里,当您说10
,这是换行的ASCII值。 如果您更改此设置:
aoutput: db "%d", 10, 0
对此:
aoutput: db "%d ", 0
您的值将用空格(而不是换行)分隔。
在序列的最终值之后,您可以打印一个孤独的换行符:
push 0x0A ; New line character
call putchar
我发现了这一点(与其他答案相同,只是在看到它发布之前就发现了)。
我知道了,我将格式定义更改为:
aoutput: db "%d ", 0 ; output format
从:
aoutput: db "%d ", 10, 0 ; output format
并添加了换行符格式以在末尾添加新行。
newline: db "", 10, 0 ; newline format
问题是您要在每个元素之后输出换行符。
以下是两个解决方案。 正如现有的两个解决方案一样,它们都没有留下尾随空白的问题。
请注意,我对循环进行了一些重新排列,以允许使用空数组。 即使没有必要,允许空数组也是一种好习惯,因为它不需要任何额外的说明。
解决方案1:如果它是最后一个元素,则使用"%d\\n"
作为格式,否则使用"%d "
。
如果您不想为空数组打印换行符,这很好。
format1: db "%d ", 0
format2: db "%d", 10, 0
jmp .loop3
.loop1:
mov eax,format1
cmp ecx,1
jnz .loop2
mov eax,format2
.loop2
push ecx
push dword [array + esi]
push dword eax
call printf
add esp, 8
pop ecx
add esi, 4
.loop3:
loop .loop1
解决方案2:如果是第一个元素,请使用"%d"
作为格式。 否则,请使用" %d"
作为格式。 在循环之后打印换行符。
如果您要打印换行符(即使是空数组)也很好。
format1: db "%d", 0
format2: db " %d", 0
mov eax, format1
jmp .loop2
.loop1:
push ecx
push dword [array + esi]
push dword eax
call printf
add esp, 8
pop ecx
add esi, 4
mov eax, format2
.loop2:
loop .loop1
push 10
call putchar
请原谅任何错误; 我上次为它编写程序集时,x86没有eax
寄存器。 在任何情况下,逻辑都应显而易见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.