Counting values in file, struct
Mar 23, 2011 at 9:26pm UTC
10 or so values in a file, only shows up one when compiled and ran. I know the problem is with the element "numElements" in my code which is part of a struct.
The code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
const int SIZE = 10;
struct Node
{
char name[30];
int ID;
int distance;
};
struct Node2
{
Node content[SIZE];
int numElements;
};
void Read(ifstream& inFile, Node2& file);
void bubbleSort ();
void Print(Node2& file);
int main ()
{
Node2 file;
ifstream inFile;
inFile.open("a6.txt" );
if (!inFile)
{
cout << "Cannot open file." << endl;
return 0;
}
Read (inFile, file);
Print(file);
system ("Pause" );
}
void Read(ifstream& inFile, Node2& file)
{
int count = 0;
while (inFile)
{
inFile >> file.content[count].name
>> file.content[count].distance
>> file.content[count].ID;
}
count++;
int numElements = 10;
file.numElements = count;
}
void Print(Node2& file)
{
for (int count = 0; count < file.numElements; count++)
{
cout << file.content[count].name << " "
<< file.content[count].distance << " "
<< file.content[count].ID;
}
}
Question is, how do i count the number of values in the file for numElements to be initialized where values are in a block of name, distance and ID.
Last edited on Mar 23, 2011 at 9:39pm UTC
Mar 23, 2011 at 10:03pm UTC
I think your count++ on line 59 needs to be inside the while loop. It should work then, though you may want to consider what happens if there is an error reading from the file.
Mar 23, 2011 at 10:06pm UTC
oh sweet, I got it now, thank you.
Always get tripped up on easy fixes.
Topic archived. No new replies allowed.