C - 从文本文件填充结构
我有一个文本文件,其中包含一些我想读取的数字。
我的文本文件如下所示。
1 2 3 5 0
2 5 8 5 0
7 8 6 9 0
我想将此文本文件读入此结构:
struct numbers num[]
我的结构定义如下:
struct numbers {
int totalnumbers;
};
第一次将进入该结构:
1 2 3 5 0
第二次:
2 5 8 5 0
依此类推,直到文件末尾。
预先非常感谢您的帮助。
I have a text file filled with some numbers that I would like to read.
My text file looks like this.
1 2 3 5 0
2 5 8 5 0
7 8 6 9 0
I would like to read this text file into this structure:
struct numbers num[]
My struct is defined like this:
struct numbers {
int totalnumbers;
};
The first time this would go into the structure:
1 2 3 5 0
And th second time:
2 5 8 5 0
And so on unitl the end of the file.
Thank very much in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的建议是参考您的课程笔记/教科书并开始编写代码。
老实说,从这里的答案中获取完整的程序你不会学到任何东西。
在文件中发送到控制台(提示
fopen
和fgets
. . .我想,已经有一段时间了) 。strtok
)字符串)到整数(提示更喜欢
strtol
而不是atoi
),编程就是关于除法和除法的。征服,实际上就是一次解决一个小问题,直到解决大问题。
希望这有帮助。
My advice is to refer to your course notes/textbook and start writing code.
Honestly you will learn nothing by taking a completed program from the answers here.
in the file to the console (hint
fopen
andfgets
. . . I think, it's been a while).strtok
)strings) to integers (hint prefer
strtol
overatoi
)Programming is all about divide & conquer, which is really just solving the little problems one at a time until the big problems are solved.
Hope this helps.
您可以使用 strtok(input, " \n") ,然后使用 atoi() 将获得的字符串转换为数字
you could use strtok(input, " \n") and then convert the strings you get to numbers using atoi()
您可以对要读取的每个值使用 scanf("%i", ) 。
这有点危险,因为它很容易使程序崩溃,而且很难找出文件中有多少记录(如果文件中的第一个值告诉您具有有意义内容的行数,则可以避免后一个问题)
另一种可能性是使用 fgets() (而不是 gets())读取一行,并使用 strtok() 或解析该行的自定义循环对其进行标记(不推荐,编写起来很混乱,会产生意大利面条代码并且容易受到攻击)到错误)。
You could use scanf("%i", ) for each value you want to read.
It's a bit dangerous because its easy to crash the program and because it's difficult to find out how much records are there in the file (The latter problem may be avoided if the first value in the file tells you the number of lines with meaningful content)
Another possibility is to read a line using fgets() (not gets()), and to tokenize it either with strtok() or a custom loop which parses the line (not recommended, it's messy to write, produces spaghetti code and is vulnerable to bugs).