Hi I have an assignment to write a C++ Program using structure and arrays. I rea
ID: 3621768 • Letter: H
Question
Hi I have an assignment to write a C++ Program using structure and arrays. I really need help with the first part. Here is the assignment:
In this assignment, you use structure and structure array to store and process information.
The structure is defined as
struct Node {
char name[30];
int ID;
int distance;
};
This assignment has five parts:
(1) Write a function that will read in the data of a group of persons from a7.txt, and
store them in an array of structures (struct Node). The number of persons should not be more than 10. Print out (cout) the information of every person in this structure array, just as they appear in a7.txt. Note that the print out must be based on the info in the structure array.
Here is the a7 text:
April,Joe
3120
90
Matthews,Jocob
4592
88
Garfield,Kitty
8917
79
Lake,Bill
2233
85
Johnson,Jim
5672
67
Zumistan,Kim
6750
76
Larson,Mike
6718
99
Anderson,Eva
5672
80
This is what my guess has been so far, but it is saying the getline function doesn't work:
#include
#include
#include
using namespace std;
struct Node
{
string name;
int ID;
int distance;
};
void read (int people[]);
int main()
{
system ("PAUSE");
return 0;
}
void read (int people[])
{
fstream myfile;
myfile.open("a7.txt");
if(!myfile)
{
cout << "Cannot open " << "a7.txt" << "." << endl;
cout << endl;
system ("PAUSE");
Node people[10];
while (!myfile.eof())
{
getline(myfile, people[].name);
getline(myfile, people[].ID);
getline(myfile, people[].distance);
}
myfile.close();
}
Thank you so much!
Explanation / Answer
Hope this helps. Let me know if you have any questions. Please rate. :) the getline was complaining for two reasons. (One actual reason, and one reason that I just suggest changing.) First the one I suggest changing - declare your input file as an ifstream (input file stream) instead of just a generic file stream. Then you can't go wrong by accidentally outputting to it and overwriting your file. The actual reason was that it takes a parameter of type string, but the ID and distance aren't string values so they aren't valid. Here's how you can fix it: #include #include #include using namespace std; struct Node { string name; int ID; int distance; }; int read (Node people[]); void print(Node people[], int num); int main() { Node people[10]; int i = read(people); coutRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.