0

I am passing a text file of integers to a function by reference. They are separated by a new line. I am wanting to push them into a new array in the function. I can count the number of lines no problem, and I use that variable to create the array of that given size, so a vector is not necessary. But when I print what should be the contents of my array it is way off. Do I need to convert the integers from the file into int values again (since I am reading from a text file, is it reading them as strings?) Help?

C++ Code:

void myFunction(ifstream& infile)
{
    int NumberOfLines = 0;
    int index;
    string line;
    //Count the number of lines in the file
    if(infile.is_open())
    {
        while(getline(infile, line))
        {
            ++NumberOfLines;
        }
    }
    int arr[NumberOfLines];
    //Put the numbers into an array
    while(!infile.eof())
    {
        infile>>arr[NumberOfLines];
    }
    //Print the array
    for(int i=0; i<NumberOfLines; i++)
    {
        cout<<arr[i]<<endl;
    }
}
cparks10
  • 277
  • 2
  • 14
  • "I use that variable to create the array of that given size" This is actually illegal in C++. It is allowed by extension by some C++ compilers, but it's use is not recommended. A) doesn't work with all compilers. B) It's a really easy way to overflow your stack (or whatever is used for automatic storage) 3) It makes an absolute horrorshow out of the `sizeof` operator. Use the `vector`. This sort of thing is exactly what it is for. – user4581301 Apr 01 '17 at 03:42
  • 1
    `while(!infile.eof())` is a common bug. Read more here: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – user4581301 Apr 01 '17 at 03:43
  • 1
    `infile>>arr[NumberOfLines];` writes out of bounds (even if the compiler supports this array, the lat valid index is `NumberOfLines-1` – M.M Apr 01 '17 at 04:01

1 Answers1

1

When you first scan the file, in order to count the lines, the ifstream position indicator reaches the end of the file.

In order to read the file again, you should reset the position indicator to the beginning, using:

infile.seekg(0, std::ios_base::beg);

More info: seekg, ifstream

mcrlc
  • 137
  • 5