if statement do not work?

Why does my if statement do not work?

void student::writeLongRecord_2() //add another student data
{
int i;
float mark;
int long number;
string array[4];
int y;
string line;
ofstream aFile;
ifstream x("student.txt");

if(x.is_open())
{
while (! x.eof() )
{

getline (x,line);
array[y] = line;
y++;
}
x.close();

if (y < 4)
{
cout <<"Enter registration number:" << endl;
cin >> number;

cout << "Enter assignment mark:" << endl;
cin >> mark;

i=i+1;
aFile << i << " " << studentRegNo << " " << fixed << setprecision(1) << studentAssignmentMark << endl;
}
}
return;
}
}
Which if statement does not work?
The one below. It does not write the studentRegNo and studentAssignmentMark in the aFile text. Why is that?

if (y < 4)
{
cout <<"Enter registration number:" << endl;
cin >> number;

cout << "Enter assignment mark:" << endl;
cin >> mark;

i=i+1;
aFile << i << " " << studentRegNo << " " << fixed << setprecision(1) << studentAssignmentMark << endl;
}
}
return;
}
closed account (zb0S216C)
You never opened the file. To open the file, if you don't already know, use this method:
 
aFile.open( "Filename.txt" );
Last edited on
You didn't initialize y to 0. So you start with a random number.

@ Framework
The constructor opens the file
closed account (zb0S216C)
The constructor opens the file

Are you referring to the ifstream instance of x? If so, I'm not. I'm referring to ofstream instance of aFile. The constructor doesn't open the file by default in either instance. However, if the file's name is given as a constructor argument, the file is opened.

Read this before telling people they're wrong: http://www.cplusplus.com/reference/iostream/ofstream/ofstream/
Last edited on
Framework wrote:
Are you referring to the ifstream instance of x?
Yes I should have stated it. I didn't consider 'aFile' since 'y' is his first problem (which even might lead to a crash)
thanks for replying guys. I already sorted out my problem. Many thank to you.. :)
Topic archived. No new replies allowed.