从文件中读取整数

编程入门 行业动态 更新时间:2024-10-26 06:32:38
本文介绍了从文件中读取整数-逐行读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在C ++中,如何从文件读取整数到整数数组?因此,例如,该文件的内容:

How can I read integers from a file to the array of integers in c++? So that, for example, this file's content:

23 31 41 23

将变为:

int *arr = {23, 31, 41, 23};

我实际上有两个问题有了这个。首先是我真的不知道如何逐行阅读它们。对于一个整数,这将非常容易,只需 file_handler>>数字语法就可以了。

I actually have two problems with this. First is that I don't really know how can I read them line by line. For one integer it would be pretty easy, just file_handler >> number syntax would do the thing. How can I do this line by line?

对我来说,似乎更难克服的第二个问题是-我应该如何为这件事分配内存? :U

The second problem which seems more difficult to overcome for me is - how should I allocate the memory for this thing? :U

推荐答案

std::ifstream file_handler(file_name); // use a std::vector to store your items. It handles memory allocation automatically. std::vector<int> arr; int number; while (file_handler>>number) { arr.push_back(number); // ignore anything else on the line file_handler.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); }

更多推荐

从文件中读取整数

本文发布于:2023-07-06 07:54:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047553.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!