将文件中的数据读入数组
如果我有一个类似于以下内容的选项文件:
size = 4
data = 1100010100110010
并且我有一个 2d size * size 数组,我想将数据中的值填充到其中,那么最好的方法是什么?
为了澄清,对于我的例子,我想要一个像这样的数组:
int[4][4] array = {{1,1,0,0}, {0,1,0,1}, {0, 0,1,1}, {0,0,1,0}}。 (不是真正的代码,但你明白了)。
不过,大小实际上可以是任何数字。
我想我必须读取大小,maloc 一个数组,然后读取一个充满数据的字符串,然后循环遍历数据中的每个字符,将其转换为 int 并将其粘贴在适当的索引中?但我真的不知道如何去做,已经搜索了一段时间但没有运气。
任何帮助都会很酷! :)
If I have an options file along the lines of this:
size = 4
data = 1100010100110010
And I have a 2d size * size array that I want to populate the values in data into, what's the best way of doing it?
To clarify, for the example I have I'd want an array like this:
int[4][4] array = {{1,1,0,0}, {0,1,0,1}, {0,0,1,1}, {0,0,1,0}}. (Not real code but you get the idea).
Size can be really be any number though.
I'm thinking I'd have to read in the size, maloc an array and then maybe read in a string full of data then loop through each char in the data, cast it to an int and stick it in the appropriate index? But I really have no idea how to go about it, have been searching for a while with no luck.
Any help would be cool! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要忘记在程序结束前删除数组;
Don't forget delete array before program ends;
循环。
我不确定 fgetc() 语法。只需检查一下即可。它一次读取一个字符。
Loops.
I am not sure with the fgetc() syntax.. Just check on it. It reads one character at a time.