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

I am writing a program that does various functions. The first problem that I am

ID: 3547389 • Letter: I

Question

I am writing a program that does various functions. The first problem that I am having is that when the program reads in the data file, it is supposed to read each of the first three lines in as individual strings and then read in the data after that into an array. This is the short version of my program:


#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main ()
{
const int size=30;

string filename;
ifstream inFile;
string qLine1, qLine2, qLine3;
double t[size], d[size];

cout<<"Please enter the file name from the listed files: "<<endl;
cout<<"CAR1.dat, CAR2.dat, CAR3.dat, or CAR4.dat)"<<endl;
cin>>filename;

inFile.open(filename.c_str());
if (!inFile.good())
{
cout<<"Could not open file"<<endl;
system ("pause");
return 1;
}

while (!inFile.eof())
{
getline(inFile, qLine1);

getline(inFile, qLine2);

getline(inFile, qLine1);
cout<<qLine1<<endl<<qLine2<<endl<<qLine3<<endl;
}


for (int i=3;i<=size;i++)

{

inFile>>t[i]>>d[i];

cout<<t[i]<<d[i]<<endl;

cout<<endl;

}


inFile.close();


system("pause");
return 0;
}


and the data file it is reading from looks like this:


Test vehicle: Car #1
Test date: October 26, 2007
Driver: D. Myers
0.0 0.0
0.2 5.5
0.4 15.9
0.6 30.9


The getline that I am using seems to be reading all of the data in the file and then assigning sequentially each line to one of my string variable. Then where the program is supposed to read the data into an array I just get garbage. This has me stumped. Any help with this would be greatly appreciated and an explaination would be even better! Thanks!

Explanation / Answer

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
const int size=30;
int i=0;
string filename;
ifstream inFile;
string qLine1, qLine2, qLine3;
double t[size], d[size];
cout<<"Please enter the file name from the listed files: "<<endl;
cout<<"CAR1.dat, CAR2.dat, CAR3.dat, or CAR4.dat)"<<endl;
cin>>filename;
inFile.open(filename.c_str());
if (!inFile.good())
{
cout<<"Could not open file"<<endl;
system ("pause");
return 1;
}
// first get first line
getline(inFile, qLine1);
// second get first line
getline(inFile, qLine2);
// third get first line
getline(inFile, qLine3);
cout<<qLine1<<endl<<qLine2<<endl<<qLine3<<endl;
// now we are already read first three lines of file.
// now till end of file...start reading first and second...double values.
while (!inFile.eof())
{
inFile>>t[i]>>d[i];
cout<<t[i]<<" " << d[i]<<endl;
i++;
}
// now close file .
inFile.close();
system("pause");
return 0;
}

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