Assignment Question: Read and parse each line in the data file credit.txt and store the data in appropriate variables. This is what I have, and it isn't even compiling, and I am not entirely sure what I did wrong. If someone could give me some insight and explain to me the problem, it would be much appreciated.
#include <iostream>
#include <cmath>
#include <math.h>
#include <fstream>
#include <string>
#include <numeric>
usingnamespace std;
int main()
{
string getline;
int number1;
ifstream infile;
string firstname;
string lastname;
string email;
float num;
float total;
float x;
float aver;
x=0; total=0;
infile.open("credit.text");
while(!infile.eof())
{ {
getline (infile,firstname,'\t');
getline (infile,lastname,'\t');
getline (infile,num,'\t');
getline (infile,email,'\t');
cout << firstname << lastname << num << email;
total=total+num;
x++;
}
aver=(total-num)/(x-1);
cout << "The last number in this range is: " <<num<< "\n";
cout<< "The sum of this range is: " <<(total-num)<<'\n';
cout<< "The number of items in this range is: "<<x-1<<'\n';
cout<< "The average of this range is: "<<aver<<'\n';
cout<< ""<<'\n';
infile.close();
getchar();
return 0;
}
26 { {
Well the first problem is you have an excess of opening braces compared to closing braces.
> getline (infile,num,'\t');
Next you're treating num as if it were a string, whereas it's a float.
Perhaps make num a string, then do some kind of string-to-float conversion at line 32.
> while(!infile.eof())
eof() doesn't work as you think it does.
If the file is empty, then eof() isn't immediately true. eof() only becomes true when some file operation (getline or >> for example) has failed.
Assuming well-formed lines for the moment, you could try
1 2 3 4 5 6
while(getline (infile,firstname,'\t'))
{
getline (infile,lastname,'\t');
getline (infile,num,'\t');
getline (infile,email,'\n'); // perhaps \n rather than \t for the last field.
}
I have completely redone most of the code, to make it a little easier on myself.
Now, the code compiles. BUT, when it compiles the answers are not what they should be.
My professor said the Average should look something like: 12345.67
and the average is coming out to -0.
cout << "The last number in this range is: " <<num<< "\n";
cout<< "The sum of this range is: " <<(total-num)<<'\n';
cout<< "The number of items in this range is: "<<x-1<<'\n';
cout<< "The average of this range is: "<<aver<<'\n';
cout<< ""<<'\n';
Even when I try the debugger it still gives me the same answers, there must be something wrong with my equation, and I have tried so many different ways, and one time I got average="nan".
So I get an answer that is a lot closer to the one I was supposed to get, I can probably figure it out from here, I will repost if I need help. I cannot believe I even put .text, that is not like me at all, haha.