Issue
My program is not printing what i want it to print.
#include<cstdlib>
#include<cmath>
#include<fstream>
#include<sstream>
#include<iomanip>
#include<iostream>
#include<string>
#include<cstring>
#include<cassert>
#include<ctime>
#include<cctype>
#include<algorithm>
#include<locale.h>
#include<stdio.h>
#include<functional>
#include<math.h>
using namespace std;
int main(int argc, char**argv)
{
int r = 0;
int p = 0;
int c = 0;
string names[20];
double scores[20][10];
ifstream infile;
infile.open("C:\\Users\\Colin\\Documents\\NetBeansProjects\\Bowlerspart2\\data\\bowlers.txt");
while(!infile)
{
cout << "can not find file" << endl;
return 1;
}
for(r = 1; r <= 10; r++)
{
getline(infile, names[r]);
for(c = 1; c <= 3; c++)
{
infile >> scores[r][c];
}
}
infile.close();
for(r = 1; r <= 10; r++)
{
cout << names[r] << endl;
cout << fixed << setprecision(2) << endl;
cout << scores[r][c] << endl;
}
return 0;
}
It only prints one of the names and prints 0.00 for all the scores. I believe I'm probably reading the file wrong, but not sure how.
Here is the text file:
Linus too good
100
23
210
Charlie brown
1
2
12
Snoopy
300
300
100
Peperment Patty
223
300
221
Pig Pen
234
123
212
Red Headed Girl
123
222
111
Marcey
1
2
3
Keith hallmark
300
300
250
Anna hallmark
222
111
211
Roxie hallmark
100
100
2
this is the output I get with my code:
Linus too good
0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00
The output is followed by multiple blank lines if I comment out the printing of the scores array. I manipulated the parameters of the for loops and nothing seems to work right. Could someone point me in the right direction?
Solution
for(c = 1; c <= 3; c++)
{
infile >> scores[r][c];
}
You expect to have one integer on a single line. Read the whole line and convert to double
:
for(c = 1; c <= 3; c++)
{
string temp;
getline(infile, temp);
scores[r][c] = std::stod(temp);
}
Your print function keeps printing the same scores[r][c]
which stores the initialization value (zero in this case). You forgot to loop through the value like this:
for(r = 1; r <= 10; r++)
{
cout << names[r] << endl;
cout << fixed << setprecision(2) << endl;
for (c = 1; c <= 3; c++)
cout << scores[r][c] << endl;
}
Note that scores[r][c] = std::stod(temp);
needs exception handling if temp
cannot be converted to double
.
try
{
scores[r][c] = std::stod(temp);
}
catch(...)
{
//add error handling
}
You can add additional error handling and start at zero index as suggested in comments
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
...
for(int r = 0; r < 10; r++)
{
if(!getline(infile, names[r]))
break;
for(int c = 0; c < 3; c++)
{
string temp;
if(!getline(infile, temp))
break;
try
{
scores[r][c] = std::stod(temp);
}
catch(...)
{
}
}
}
for(int r = 0; r < 10; r++)
{
cout << names[r] << endl;
cout << fixed << setprecision(2) << endl;
for (int c = 0; c < 3; c++)
cout << scores[r][c] << endl;
}
Answered By - Barmak Shemirani
Answer Checked By - Candace Johnson (JavaFixing Volunteer)