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

C++ Read array from file in specified range

本文关键字:文件 读取 数组 范围内 C++      更新时间:2023-10-16

我有一个包含如下数组的文件:

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;
}