943,522 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 367
  • C++ RSS
Sep 1st, 2008
0

help please

Expand Post »
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.

C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. using namespace std;
  5.  
  6.  
  7.  
  8. int main() {
  9.  
  10. const int CAPACIDAD = 100;
  11. int array[CAPACIDAD];
  12. int num1, num2, pos = 0;
  13. ifstream Entrada;
  14.  
  15.  
  16. Entrada.open("entrada.txt");
  17.  
  18.  
  19. Entrada >> num1 >> num2;
  20.  
  21. while(!Entrada.eof())
  22.  
  23. {
  24.  
  25. array[pos] = num1;
  26.  
  27. cout << num1;
  28.  
  29. array[CAPACIDAD - pos - 1] = num2;
  30.  
  31. cout << "\t" << num2 << endl;
  32. pos++;
  33.  
  34.  
  35. Entrada >> num1 >> num2;
  36. }
  37.  
  38.  
  39. cin.ignore();
  40. return 0;
  41. }

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
Last edited by lmastex; Sep 1st, 2008 at 2:50 am.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
lmastex is offline Offline
17 posts
since Jan 2008
Sep 1st, 2008
0

Re: help please

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:
C++ Syntax (Toggle Plain Text)
  1. while( Entrada >> num1 >> num2 )
  2. {
  3. //do the processing
  4. }
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.
Reputation Points: 1268
Solved Threads: 228
Posting Virtuoso
vmanes is offline Offline
1,895 posts
since Aug 2007

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Practice Problem, strstr() function
Next Thread in C++ Forum Timeline: int *array[10] to dynamic array equivalent?





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC