我不明白如何将字符串转换为整数。
这是家庭作业,但我不想要这个问题的答案——(AKA 正确代码)。如果有人能解释我做错了什么,我将不胜感激!:(
提前致谢!!!
我在 32 位虚拟机上运行 Ubuntu 12.04。
我编译:
nasm -f elf proj2.asm
我链接:
gcc -o proj2 proj2.o
然后运行它:
./proj2
它显示第一个数字,但是当我尝试使用atoi
.
我有一位老师希望我们:
从按如下方式排列的文本文件中读取数字:
4 5 4 2 9
(每个整数前都有空格)
0x0D
根据他的指示:“请务必将七 (7) 个字符读入缓冲区以获取整行。这些是代表数字的五个字符以及字符 CR 和 LF。CR 是带有十六进制代码和 LF的回车符是带有十六进制代码的换行符0x0A
。")
我已经从文件中删除了空格,并尝试以这种方式读取它,但它没有帮助。
整数将被读取到堆栈上的一个数组中,最大整数数为 250。但这不是问题:/
以下是我到目前为止的代码。
BUFFERSIZE equ 10
section .data
file_name: db "/home/r/Documents/CS/project2/source/indata.txt", 0x00
file_mode: db "r", 0x00
output: db "%i",0xa
test: db "hello world",10
format: db "%u"
numToRead: db 1
temp: db "hi"
num:db "1",0,0
section .bss
fd: resd 4
length: resd 4
buffer resb BUFFERSIZE
;i was trying to use buffers and just
;read through each character in the string,
;but i couldn't get it to work
section .text
extern fopen
extern atoi
extern printf
extern fscanf
extern fgets
extern getc
extern fclose
global main
main:
;setting up stack frame
push ebp
mov ebp, esp
;opens file, store FD to eax
push file_mode
push file_name
call fopen
;save FD from eax into fd
push eax
mov ebx,eax
mov [fd],ebx
;ebx holds the file descriptor
;push in reverse order
push ebx
push numToRead
push temp
call fgets
push eax
call printf ;prints length (this works, i get a 4.
;Changing the number in the file changes the number displayed.
;I can also read in several lines, just can't get any ints!
;(So i can't do any comparisons or loops :/ )
;i shouldn't need to push eax here, right?
;It's already at the top of the stack from the printf
;pop eax
;push eax
call atoi
;calling atoi gives me a segmentation fault error
push eax
call printf
mov esp,ebp
pop ebp
ret
编辑:有趣的是,我可以调用 atoi 就好了。那是我尝试的时候
push eax
call atoi
push eax
call printf
我得到分段错误。