I am new to C++ and lately I was having trouble reading a file. That problem is now fixed. What I'd like to do now is to use the file I read to create an array, but all this has to be done in a function, this means the function has to return an array so I can use it on the main. The process I follow:
- Read File
- Create Array
- Return Array Adress.
In the main: Use function to put an array in a variable. My code so far:
#include <iostream> #include <fstream> #include <cstdlib> #include <string> using namespace std; void imprimeArreglo (int[],int); int* leeArreglo(string&); int i; void imprimeArreglo(int a[]) { cout << a[i] << endl; } int* leeArreglo(string nombre) { ifstream arch(nombre.c_str()); string tamStr; int tam; if(arch.is_open()) { getline(arch,tamStr); tam=atoi(tamStr.c_str()); int arr[tam]; for(int i=0;i<tam;i++) { arch >> arr[i]; } int *ret=arr; return ret; } return 0; } int main() { string nombre = "arr.txt"; int *a= leeArreglo(nombre.c_str()); imprimeArreglo(a); return 0; }What my
arr.txtfile looks like:10 9 8 22 33 76 0 23 100 -8 45
I think this should print (with imprimeArreglo(a)):
9 8 22 33 76 0 23 100 -8 45
But the only thing I get in the console is:
2292592 Which I think it's a memory adress??? What am I doing wrong? Is there a better way to do it without using vectors?
Thanks in advance!
int arr[tam];variable length arrays are a non-standard extension. b) Why would you not want to use vectors?typedef std::istream_iterator<int> istr_it; std::copy(istr_it(arch), is_it(), std::back_inserter(arr));Vector only takes two lines of code compared to your 20ish. And it's faster, and it works.