Match Solution Output Exactly

closed account (SNhURXSz)
Here is my code:

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

using namespace std;

int main ()
{
int numStudents;

cout << "Enter class size: " << endl;
cin >> numStudents;

if (numStudents < 1)
{
cout << "Invalid Input: Class must have at least 1 student" << endl;
}
else if (numStudents > 25)
{
cout << "Invalid Input: Class size is restricted to 25" << endl;
}


string name[25];

for (int student=1;student <= numStudents; student++)
{
ifstream inputFile;
inputFile.open("LineUp.dat");

int i = 0;
while (!inputFile.eof())
{
inputFile >> name[i];
++i;
}

inputFile.close();
}

string temp;

for (int j=1;j<numStudents;++j)
{
temp = name[j];
int k;

for (k = j-1; k>=0 && name[k] > temp; k--)
{
name[k+1] = name[k];
}

name[k+1] = temp;
}

cout << name[0] << " should be at the front of the line." <<endl;
cout << name[numStudents-1] << " should be at the end of the line." <<endl;

return 0;
}


My goal is to match my professors output exactly.
When I test my code against his I get the following errors:

(I do not know how to upload pictures on this forum so I have a TinyPic link)
[IMG]http://i43.tinypic.com/15ot3pe.png[/IMG]

or

http://i43.tinypic.com/15ot3pe.png

What am I doing wrong? I am stumped!

****My code is on the left. My professors is on the right.
You can preserve the format of your code by enclosing it in [ code ] [ /code ] tags (without the spaces.)

this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	string name[25];

	for (int student=1;student <= numStudents; student++)
	{
		ifstream inputFile;
		inputFile.open("LineUp.dat");

		int i = 0;
		while (!inputFile.eof())
		{
			inputFile >> name[i];
			++i;
		}

		inputFile.close();
	}


is silly.

What purpose does the for loop serve? Other than to open the file and read from it numStudents number of times?

The while loop doesn't work as you expect. After it reads 25 students from the file, eof has still not been encountered. your final time through the loop, it is encountered but name[25] is evaluated anyway causing you to access memory you don't own. It's very, very rare that eof should signal the end of a loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
	string name[25];

	int students = 0 ;

	ifstream inputFile("LineUp.dat");

	while (students < numStudents  &&  (inputFile >> name[students]))
		++students ;

	if ( students != numStudents )
	{
		// do something appropriate
	}





Last edited on
Topic archived. No new replies allowed.