C++ 从指定范围内的文件中读取数组

标签 c++ arrays

<分区>

我有一个包含这样数组的文件:

5
23
232
44
53
43

所以行包含元素的数量。这意味着需要读取的元素数量。并创建一个数组。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
fstream mystream("file.txt");
int ArraySize;
int* array;

ArraySize = ......... //read first line

for(int i = 2; i < ArraySize; i++){
...............//add elements to the array
}

最佳答案

您可以像对待 std::cin 一样对待 std::ifstream...

#include <fstream>
#include <iostream>

int main() {

    std::ifstream fs("/tmp/file.txt");

    int arr_size;
    fs >> arr_size; // gets first number in file.

    int* arr = new int[arr_size]; // could also use std::vector

    // collect next arr_size values in file.
    for (int i = 0; i < arr_size; ++i) {
        fs >> arr[i];
    //  std::cout << arr[i] << ' ';
    }

    delete [] arr;

    return 0;
}

关于C++ 从指定范围内的文件中读取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45045959/

相关文章:

c++ - C++/pthread/join错误信息 "what(): Invalid argument"的含义

c++ - std::string、wstring、u16/32string 说明

c++ - 使用无符号字符数组处理单个字节

c++ - std::enable_if 在模板参数上确定 STL 容器

c++ - 对 std::string 数组进行二进制搜索

arrays - 如何使用带 Angular 复选框过滤对象数组?

javascript - 检查数组是否与另一个数组匹配以返回不匹配的内容

javascript - 如何使用字符串数组过滤嵌套对象

c++ - 模板类中的方法仅对某些模板参数正确

c - 有没有一种 O(n) 的方法来绘制二维数组网格而不是 C 中的 O(n²)?