Hey guys. I'm just trying out something with the fstream library. In the next code, I'm trying to read from the beginning of the array (num1) and from the end of the array (num2) the file I have as an "entry" called "entrada.txt", which has the numbers 1 up to 12. I want the program to show me in the first cout inside the while loop the first 6 numbers, from 1 to 6, and in the 2nd cout, numbers from 12 to 7. This is what i have so far.

#include <iostream>
    #include <fstream>
    
    using namespace std;
    
   
    
    int main() {
    
    const int CAPACIDAD = 100;
    int array[CAPACIDAD];
    int num1, num2, pos = 0;
    ifstream Entrada;
   
    
    Entrada.open("entrada.txt");
   
    
    Entrada >> num1 >> num2;
    
    while(!Entrada.eof())
    
    {
    
    array[pos] = num1;
    
    cout << num1;
    
    array[CAPACIDAD - pos - 1] = num2;
    
    cout << "\t" << num2 << endl;
    pos++;
    
    
    Entrada >> num1 >> num2;
    }
    
   
    cin.ignore();
    return 0;
    }

When I run the program, all I get is this:
1 2
3 4
5 6
7 8
9 10

It doesn't even get to 12.

Do you know whats the problem. If you have any questions ask me =)... thanks ;)

Does your data file end with a newline? That is, after typing "12", do you hit the enter key?

When using eof( ) to test for end of data, that's usually a crucial requirement of the data file.

Try controlling your loop thusly:

while( Entrada >> num1 >> num2 )
   {
        //do the processing
    }

If the read action is successful, you'll enter the loop body. However, in this form, you must have an even number of data elements in the file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.