0

I have a file which contains array like this :

5
23
232
44
53
43

so line contains number of elements. Which means number of elements need to read. And create a array.

#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
}
nooogii
  • 25
  • 4
  • There is no single question mark in your **question**. What do you want from us? Guess? Specify what's the problem. This is not a code providing site – Fureeish Jul 11 '17 at 23:24
  • 1
    u really want SO to provide code for `//read first line`? – pm100 Jul 11 '17 at 23:30

1 Answers1

3

You can treat a std::ifstream as you would std::cin...

#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;
}
Charles
  • 1,384
  • 11
  • 18