在AT& T组件中调用printf和scanf

时间:2014-05-13 22:14:23

标签: c assembly printf scanf att

我有以下代码:

.align 32

.data
input1: .string "Give short: \n"
input2: .string "Give char: \n"
arg1: .string "%hu"
arg2: .string "%c"
output1: .string "%hu\n"
output2: .string "%c\n"
short: .short 1
char: .byte 1

.global main

main:
pushl %ebp
movl %esp, %ebp

pushl $input1
call printf
addl $4, %esp

pushl $short
pushl $arg1
call scanf
addl $8, %esp

pushl (short)
pushl $output1
call printf
addl $8, %esp

pushl $input2
call printf
addl $4, %esp

pushl $char
pushl $arg2
call scanf
addl $8, %esp

pushl (char)
pushl $output2
call printf
addl $8, %esp

movl %ebp, %esp
popl %ebp
ret

我想输入short,打印它,输入char并打印它,但是在打印'Give char'程序结束后留下两个空行。有什么想法吗?当我在一个函数调用中获取参数时,它正在工作。

1 个答案:

答案 0 :(得分:0)

这是一个直截了当的C问题,它与汇编代码无关。您应该再次阅读scanf文档。它只处理任何初始部分可以转换为数字,其余的输入留在缓冲区中。对于表现良好的输入,它只是终止换行符,但可以是任何东西。然后,与所有其他转换相反,%c不会自动跳过空格,因此它会很乐意接受缓冲区中的换行符。解决方案:在格式说明符使scanf跳过空格之前显式添加空格。请注意,您仍然可以在一行上提供输入。如果您不想要,则需要手动丢弃该行的其余部分,或读取行。