如何从文件中读取整数到 C++ 中的整数数组?因此,例如,此文件的内容:
23
31
41
23
会变成:
int *arr = {23, 31, 41, 23};
?
我实际上有两个问题。首先是我真的不知道如何逐行阅读它们。对于一个整数,这将非常简单,只需 file_handler >> number
语法即可。我如何逐行执行此操作?
第二个对我来说似乎更难克服的问题是——我应该如何为这个东西分配内存? :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');
}
关于c++ - 从文件中读取整数 - 逐行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16123013/