0

I have been working on this problem since last week and I about to go insane. I got it working and then all of the sudden it got screwed up. I want to know if someone can help me find out what I am doing wrong to fix it again.
Here's an example of what I have to read in.
K G Johnson 4598 85 95 72 50

Here is a the piece of my code that has me baffled:

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

int main() 
{
int classid[4], test1[3], test2[3], test3[3], final[3],  i, ;
char name[9][14];
	
for(i=0; i<=8; i++)name[i][13]='\0';
	//Open file...
	ifstream classrec;
    classrec.open("STUDNTRECS.TXT");
    ofstream output;
    output.open("STUDENTRECSOUT.TXT");
//Read file and calculate the letter grade of each student...
for(i=0; i<8; i++)
{
classrec.get(name[i],14);
classrec>>classid[i]>>test1[i]>>test2[i]>>test3[i]>>final[i]>>ws;    
       	
        
output<<name[i]<<" "<<classid[i]<<" "<<test1[i]<<" "<<test2[i]<<" "<<test3[i]<<" "<<final[i]<<endl;
    }

When I read in the file my and send it to the output file it is usually the right information, but it ends up in the wrong places. I get numbers from the class id in the character information. I have come here as a last resort to understand what it is I messed up. Please help.

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Ancient Dragon
0

The get() function will get exactly the number of characters you specify unless it first encounters the '\n' in the file or end-of-file. Line 20 is asking for 14 characters and that's exactly what you'll get. In the example line you posted it will read "K G Johnson 45", which is probably not what you intended. I think a better way of reading that file is to first read it one character at a time until the first numeric character is encountered. This code too has a couple of minor problems but probably ok for your program.

int count = 0;
int c;
while( !isdigit((c = cin.get()) )
{
    name[i][count] = c;
    ++count;
}
name[i][count] = 0; // null-terminate the string

The size of classid is one character too small -- you have to make room for the null terminating byte.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.