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;
    }
}
3
  • "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. Commented Apr 1, 2017 at 3:42
  • 1
    while(!infile.eof()) is a common bug. Read more here: stackoverflow.com/questions/5605125/… Commented Apr 1, 2017 at 3:43
  • 1
    infile>>arr[NumberOfLines]; writes out of bounds (even if the compiler supports this array, the lat valid index is NumberOfLines-1 Commented Apr 1, 2017 at 4:01

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Note: You may also need to clear() the eof flag before rewinding the file.
@user4581301 you're right in case he doesn't use c++11 or later. Since c++11 seekg does it for you.
Son of a gun. Didn't know that, but there it is in [istream.unformatted]. Very cool.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.