从文件中读取整数-逐行读取 [英] Read integers from file - line by line

查看:312
本文介绍了从文件中读取整数-逐行读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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');
}

这篇关于从文件中读取整数-逐行读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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