Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am trying to write a C++ program that creates a structure called components, t

ID: 3858851 • Letter: I

Question

I am trying to write a C++ program that creates a structure called components, then creates a vector using the structure components and pass it by reference to a function called fileinput. Here is what I have for the structure section of code:

struct component // Structure to Hold Resistor Values

{

int id; // Integer Datatype 'id' Declaration

string type; // String Datatype 'type' Declaration

string vendor; // String Datatype 'vendor' Declaration

int value; // Integer Datatype 'value' Declaration

};

Here is where I need help, with writing the function prototype and definition and the passing of the vector. This is the way I have the prototype so far:

void fileinput(vector<component> &); // Pass A Vector Of Components (Pass By Reference) ** Do I need a Variable or Parameter after the ampersand & ** ?

Then in the int main() function the vector is declared:

vector <component> r1(0); // Component Vector Declaration To Store Data

The goal is to input a text file that has 3000 resistor values. In main() the vector is declared with the structure and the r1(0) is for the first row's data when the count is 0 I guess? This part was provided already in main().

Then lastly the function definition I have so far is:

void fileinput(vector<component>& x) ** Should the ampersand & be placed directly in front of the parameter, like this: void fileinput(vector<component> &x), or does it matter? **

The main objective of this post is to make sure I have the prototype written correctly before main() and the function definition header after main() written correctly. Thanks in advance for your help! Please Help!

Explanation / Answer

#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
struct component {
   int id;
   string type;
   string vendor;
   int value;
};
void fileinput(vector<component> &);
//void fileinput(vector<component> &v); //this line also works fine without any issues
int main() {
   vector<component> v;
   fileinput(v);
   cout<<v[0].id<<" "<<v[0].type<<" "<<v[0].vendor<<" "<<v[0].value<<endl;
}
void fileinput(vector<component> &v) {
   int number_of_lines = 0;
   string line;
   std::ifstream myfile("input.txt");
   while (std::getline(myfile, line)) ++number_of_lines;
   v.resize(number_of_lines);
   v[0].id=3;
   v[0].type="hello";
   v[0].vendor="hai";
   v[0].value=35;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote