关于从文本文件中读取,我有几个问题。 [英] I have a couple questions about reading from text files.

查看:66
本文介绍了关于从文本文件中读取,我有几个问题。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是我无法弄清楚的问题。



(d)如果不访问任何scanf()变体,你会如何阅读签名

来自文本文件的整数? (假设文件是​​打开的,整数是下一个要读取的
的东西。)



(e)再次没有scanf( ),您如何从文本文件中读取实数?



我尝试过的方法:



These are the questions I can't figure out.

(d) Without access to any of the scanf() variants, how would you read a signed
integer from a text file? (Suppose the file is open and the integer is the very next
thing to be read.)

(e) Again without scanf(), how would you read a real number from a text file?

What I have tried:

I'm thinking the function fread() needs to be used but I'm not sure if this is correct.

推荐答案

因为文本文件是行分隔的,所以可以使用 fgets - C ++ Reference [ ^ ]来读取文件行将行放入缓冲区。



如果一行包含多个项目(例如空格分隔的单词或数字),则必须逐行拆分或逐项解析。这可以通过查看每个字符并停止分隔字符或使用C标准库函数来完成 strchr strpbrk - C ++参考 [ ^ ]或 strtok - C ++参考 [ ^ ]。



一旦你隔离了一个数字(如果需要),你就可以使用 atoi - C ++参考 [ ^ ], atol strtol - C ++参考 [ ^ ],atof - C ++参考 [ ^ ]或 strtod - C ++参考 [ ^ ]转换为 int long ,或 double



您也可以阅读c将文件填入文件大小为+ 1的已分配缓冲区,使用 fread 将内容读入缓冲区,设置 buffer [file_size] = 0 (附加一个NULL字节来创建一个有效的字符串),并使用上面提到的函数解析缓冲区。
Because text files are line separated, you can use fgets - C++ Reference[^] to read the file line by line into a buffer.

If a line contains multiple items (e.g. space separated words or numbers), you have to split the line or parse it item by item. This can be done by looking at each character and stopping at separation characters or using the C standard library functions strchr, strpbrk - C++ Reference[^] , or strtok - C++ Reference[^].

Once you have isolated an item (if necessary) that is a number, you can use atoi - C++ Reference[^] , atol, strtol - C++ Reference[^] , atof - C++ Reference[^], or strtod - C++ Reference[^] to convert to int, long, or double.

You may also read the complete file into an allocated buffer of file size + 1, read the content into the buffer using fread, set buffer[file_size] = 0 (append a NULL byte to create a valid string), and parse the buffer using the above mentioned functions.


这篇关于关于从文本文件中读取,我有几个问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆