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

How do I get this code to read in two text files. It breaks when I run it. I can

ID: 3761669 • Letter: H

Question

How do I get this code to read in two text files. It breaks when I run it. I can't use vectors or algotrithim so....

The code works with just one text file. When I add the second text file called "garbage.txt" the code breaks

#include
#include
#include
using namespace std;
struct partStruct {
   string partID;
   string partDescrip;
   double cost, salesPrice;
};
int readInputFromFile (partStruct myPart[]);
double calculateTotalProfitMargin(partStruct mypart[], int);
void writeNewFile(partStruct mayPart[], int, double);
void sortInput(partStruct myPasrt[], int num);
int main(){
   partStruct myPart[100];
   partStruct myGarbage[100];
   int num = 0;
   num = readInputFromFile(myPart);
   double profitMargin = 0.0;
   profitMargin = calculateTotalProfitMargin(myPart, num);
   writeNewFile(myPart, num, profitMargin);

   system("pause");
   return 0;
}
int readInputFromFile (partStruct myPart[]){

int num=0;
ifstream inFile;
inFile.open("parts.txt", ios::in);
inFile.open("garbage.txt", ios::in);

if (inFile.is_open()){
   while (num <= 100 && !inFile.eof()) {

       getline(inFile, myPart[num].partID, ',');
       getline(inFile, myPart[num].partDescrip, ',');
       inFile >> myPart[num].cost;
       inFile.ignore(1,'#');
       inFile >> myPart[num].salesPrice;
       inFile.ignore(1,'#');
       num++;
   }

   inFile.close();
  
}

else
   cout <<"The file couldn't be opened, program is closing";
   return num;
}

Explanation / Answer

Hi,

I think the problem with your program is that:

ifstream inFile;

Use 2 seperate file pointers as:

ifstream inFile1,inFile2;

I think this should solve your problem.

Note:You can actually use the same file pointer for the second file as well,For that to use you need to close the filepointer to the first pointer then only you will be allowed to use the file pointer to opne second file.In your case you need to open 2 files simultaneously you need to use 2 seperate file pointer.

Hope that helps...HAPPY ANSWERING!!!!!!

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