C++ School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Searching an array Code matches okay, but throws error when no match is found Rate Topic: -----

#1 Lattimer24  Icon User is offline

  • New D.I.C Head
  • Pip

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 29-October 08


Dream Kudos: 0

Share |

Searching an array

Posted 15 April 2009 - 12:03 PM

Greetings all!

I need a shove in the right direction with an issue I am having when comparing data in an array with data input by a user. Here is the entire homework problem:

Write a program that does the following:

Opens a data file that contains:
o On the very first line, a single integer that indicates how many student records
there are in the file
o each line after that contains a student's name, and 3 test scores (separated by
spaces)
Reads the value on the first line, and creates 3 dynamic arrays of exactly that many
elements (to store test scores) and 1 dynamic array to store the student's name
Input from the file student names and three scores each to fill all 4 arrays
Provide an interactive menu that will then allow the user to:
o display scores for a single test
- list all student names and their score for the chosen test
o display all scores and an average for a single student
- You will need to search the name array for a student first, then use the
index
- write function that takes the name array and and the student's name to look
for as parameters, and returns the index if found, -1 if not
o display class averages for the three tests, along with the high and low scores.

Here is my code:

/*********************************************/
/*  Program: Test_scores.cpp				 */
/*  Author: Doug Mainwaring				  */
/*										   */
/*  Description:							 */
/*		  Opens file of test scores and	*/
/*		  produces output based on user	*/
/*		  selections					   */
/*  Comments:								*/
/*										   */
/*********************************************/

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

using namespace std;

int search_name(const string find_name[], const string in_name, int size1);
// Function to search for an inputted student name in the name[] array

int main()
{
	int size, *test1, *test2, *test3, score1, score2, score3, choice2;
	char choice, dummy;
	string *name, student, find_student;
	ifstream infile;
	ofstream outfile;

	cout << "hello\n";

	infile.open("scores.txt");
	if (infile.fail())
	{
		cout << "Cannot open data file\nProgram halted\n\n";
		exit(1);
	}

		infile >> size;

		test1 = new int[size];
		test2 = new int[size];
		test3 = new int[size];
		name = new string[size];

		for (int i = 0; i < size; i++)
		{
			infile >> student >> score1 >> score2 >> score3;
			name[i] = student;
			test1[i] = score1;
			test2[i] = score2;
			test3[i] = score3;
		}

	do
	{
		system("cls");
		cout << "Welcome to Test Score 2000\n\n\n"
			 << "Please choose from the following:\n\n"
			<< "A.  Display all student scores for a single test\n"
			<< "B.  Display all scores and an average for a single student\n"
			<< "C.  Display class average for each test along with the highest and lowest score\n"
			<< "Q.  End Program\n\n"
			<< "<=SELECTION=> ";
		cin >> choice;
		choice = toupper(choice);

		switch (choice)
		{
			case 'A':
				{
					do
					{
						system("cls");
						cout << "Please input which test scores you would like to view - 1, 2, or 3.\n"
							 << "Input 0 to return to main menu ==> ";
						cin >> choice2;
	
						switch (choice2)
						{
							case 1:
								{
									cout << "\nTest " << choice2 << endl
										<< "========================================\n";
									for (int i = 0; i < size; i++)
										{
											cout << name[i] << "\t\t" << test1[i] << endl << endl;
										}
									cout << "\n\nHit Enter to continue....";
									cin.ignore(100,'\n');
									cin.get(dummy);
									break;
								}
						
							case 2:
								{
									cout << "\nTest " << choice2 << endl
										 << "========================================\n";
									for (int i = 0; i < size; i++)
									{
										cout << name[i] << "\t\t" << test2[i] << endl << endl;
									}
									cout << "\n\nHit Enter to continue....";
									cin.ignore(100,'\n');
									cin.get(dummy);
									break;
								}
	
							case 3:
								{
									cout << "\nTest " << choice2 << endl
										 << "========================================\n";
									for (int i = 0; i < size; i++)
									{
										cout << name[i] << "\t\t" << test3[i] << endl << endl;
									}
									cout << "\n\nHit Enter to continue....";
									cin.ignore(100,'\n');
									cin.get(dummy);
									break;
								}

							case 0:
								break;
	
							default:
								{
								cout << "\nIncorrect input, please try again!\n";
								cout << "\n\nHit Enter to continue....";
								cin.ignore(100,'\n');
								cin.get(dummy);
								}
						}
						
					} while (choice2 != 0);
				}
				break;
			
			case 'B':
				{
					do
					{
						system("cls");
						int i;
						cout << "Please choose from the following students or input QQQ to return:\n\n";

						for (int num = 0; num < size; num++)
						{
							cout << name[num] << endl;
						}
						cout << "\n==> ";
						cin >> find_student;
						i = search_name(name, find_student, size);
					
						if (i < 0)
							cout << "Name not found, please try again!\n";
	
						else
						{
							cout << "\nStudent\tTest 1\tTest 2\tTest 3\tAverage\n"
								 << "======================================="
								 << endl << name[i] << "\t" << test1[i] << "\t" << test2[i]
								 << "\t" << test3[i] << "\t" << ((test1[i] + test2[i] + test3[i]) / 3) << endl << endl;
						}
					cout << "\n\nHit Enter to continue....";
					cin.ignore(100,'\n');
					cin.get(dummy);
					} while (find_student != "QQQ" || find_student != "qqq");
				} 
				break;

			case 'C':
				{
					system("cls");
					int average1 = 0, average2 = 0, average3 = 0, hinum1, lownum1, hinum2, lownum2, hinum3, lownum3, max1 = 0, max2 = 0, max3 = 0,
						min1 = 100, min2 = 100, min3 = 100;
					for (int i = 0; i < size; i++)
					{
						average1 += test1[i];
						average2 += test2[i];
						average3 += test3[i];
						hinum1 = test1[i];
						hinum2 = test2[i];
						hinum3 = test3[i];
						lownum1 = test1[i];
						lownum2 = test2[i];
						lownum3 = test3[i];

						if (hinum1 > max1)
							max1 = hinum1;
						if (hinum2 > max2)
							max2 =hinum2;
						if (hinum3 > max3)
							max3 = hinum3;
						if (lownum1 < min1)
							min1 = lownum1;
						if (lownum2 < min2)
							min2 = lownum2;
						if (lownum3 < min3)
							min3 = lownum3;
					}

					cout << "\nTest\tAverage\t\tHigh Score\tLow Score\n"
						 << "=================================================\n"
						 << "1\t" << (average1 / size) << "\t\t" << max1 << "\t\t" << min1 << endl
						 << "2\t" << (average2 / size) << "\t\t" << max2 << "\t\t" << min2 << endl
						 << "3\t" << (average3 / size) << "\t\t" << max3 << "\t\t" << min3 << endl << endl;
				}
				cout << "\n\nHit Enter to continue....";
				cin.ignore(100,'\n');
				cin.get(dummy);
				break;
		}
	}while (choice != 'Q');

	return 0;
}

int search_name(const string find_name[], const string in_name, int size1)
{
	int index = 0, not_found = -1;

	while (in_name != find_name[index] && index <= size1)
		index++;

	if (in_name != find_name[index] && index > size1)
		return not_found;
	else
		return index;
}



When executing this code and selecting option B to display a single student, if a user inputs a name that matches, there is no problem. However, if a user inputs an incorrect name, instead of returning a -1 and reverting to the "Name not found" statement, the program crashes and refers to a "bad pointer" and "cannot evaluate expression." What am I missing here? If the input matches are returns the proper int from the function, where is the problem when attempting to return the -1 int?

Thank you in advance.

Lattimer
Was This Post Helpful? 0
  • +
  • -


#2 Lattimer24  Icon User is offline

  • New D.I.C Head
  • Pip

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 29-October 08


Dream Kudos: 0

Re: Searching an array

Posted 15 April 2009 - 05:00 PM

Bump, please help!!
Was This Post Helpful? 0
  • +
  • -

#3 David W  Icon User is offline

  • DIC supporter
  • Icon

Reputation: 130
  • Posts: 1,013
  • Joined: 20-September 08


Dream Kudos: 1075

Re: Searching an array

Posted 16 April 2009 - 12:03 AM

View PostLattimer24, on 15 Apr, 2009 - 05:00 PM, said:

Bump, please help!!


consider something like this ...

int search_name(const string find_name[], const string in_name, int size1)
{
	/*
	int index = 0, not_found = -1;

	while (in_name != find_name[index] && index <= size1)
		index++;

	if (in_name != find_name[index] && index > size1)
		return not_found;
	else
		return index;

	*/
	
	for( int i=0; i<size1; ++i )
		if( in_name == find_name[i] )
			return i;
	return -1;
}


Was This Post Helpful? 1
  • +
  • -

#4 Lattimer24  Icon User is offline

  • New D.I.C Head
  • Pip

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 29-October 08


Dream Kudos: 0

Re: Searching an array

Posted 16 April 2009 - 09:32 AM

David W,

I've seen many replies from you on numerous homework assistance requests and would like to thank you for replying to my post. After some laboring, your code was exactly the same that I came up with. The program runs just fine, mission accomplished!

Lattimer
Was This Post Helpful? 0
  • +
  • -

#5 David W  Icon User is offline

  • DIC supporter
  • Icon

Reputation: 130
  • Posts: 1,013
  • Joined: 20-September 08


Dream Kudos: 1075

Re: Searching an array

Posted 16 April 2009 - 09:16 PM

Quote

... After some laboring, your code was exactly the same that I came up with. The program runs just fine, mission accomplished!

Lattimer

Thanks for your note and the good news ...

You may like to try a version that uses an array of struct (and also to try your hand at a version that keeps to standard C++)

Shalom,
David
http://developers-he.../index.p...opic,127.0.html
Was This Post Helpful? 0
  • +
  • -

#6 janotte  Icon User is offline

  • code > sword
  • Icon

Reputation: 281
  • View blog
  • Posts: 3,102
  • Joined: 28-September 06


Dream Kudos: 0

Expert In: C/C++

Re: Searching an array

Posted 17 April 2009 - 03:36 AM

If your code really is:

View PostLattimer24, on 16 Apr, 2009 - 09:32 AM, said:

...exactly the same...

then you'd better hope your teacher believes you wrote it.
Was This Post Helpful? 0
  • +
  • -

#7 David W  Icon User is offline

  • DIC supporter
  • Icon

Reputation: 130
  • Posts: 1,013
  • Joined: 20-September 08


Dream Kudos: 1075

Re: Searching an array

Posted 17 April 2009 - 04:06 AM

P.S.

It's always good practice to code like this ...

// test if the C++ string 'name' is in the array with 'ary_size' number of names
// return the index 'i' in the array, if found ... i is in the range 0..ary_size-1
// otherwise, return -1
int get_index(const string& name, const string name_ary[], int ary_size )
{
    for( int i = 0; i < ary_size; ++i )
    {
        if( name == name_ary[i] )
        {
            return i; // found ... so return the index where it was found
        }
    }
    // else ... if reach here ... NOT found, so ...
    return -1;
}

Was This Post Helpful? 0
  • +
  • -

#8 janotte  Icon User is offline

  • code > sword
  • Icon

Reputation: 281
  • View blog
  • Posts: 3,102
  • Joined: 28-September 06


Dream Kudos: 0

Expert In: C/C++

Re: Searching an array

Posted 17 April 2009 - 05:14 AM

View PostDavid W, on 17 Apr, 2009 - 04:06 AM, said:

It's always good practice to code like this ...


Could you elaborate on what lesson / point / insight that we are to take away from the snippet posted?

Is it:
- using the "code=cpp" tag?
- including comments?
- employing the 'brackets in line' format?
- using pass by reference?
- something else?

Sorry but it has passed me by.
Was This Post Helpful? 0
  • +
  • -

#9 David W  Icon User is offline

  • DIC supporter
  • Icon

Reputation: 130
  • Posts: 1,013
  • Joined: 20-September 08


Dream Kudos: 1075

Re: Searching an array

Posted 17 April 2009 - 08:55 AM

Re. some recommendations for student hand-ins ... for top marks:

- included appropriate comments with functions re. what is
passed in and back ... and ...
what the function does, if the function name is not self explanatory
- use brackets for each block of code in if(...){ ...;}else if(...){ ...;}else{...;}
(Some schools insist on this ... others just insist on clarity of logic flow.)
- rather than passing a copy, by value, into a function, where appropriate,
pass in by const reference, especially for large C++ obj's
- use as descriptive names as possible to help 'see' the program logic flow
and to self-document, as you go, what is happening 'there' ...

This post has been edited by David W: 17 April 2009 - 09:08 AM

Was This Post Helpful? 0
  • +
  • -

#10 janotte  Icon User is offline

  • code > sword
  • Icon

Reputation: 281
  • View blog
  • Posts: 3,102
  • Joined: 28-September 06


Dream Kudos: 0

Expert In: C/C++

Re: Searching an array

Posted 17 April 2009 - 06:20 PM

Absolutely agree with every point!

If you haven't already, have you considered a tutorial expanding this out a bit?

It would be a good resource for students that we could point them at.
Was This Post Helpful? 0
  • +
  • -

#11 David W  Icon User is offline

  • DIC supporter
  • Icon

Reputation: 130
  • Posts: 1,013
  • Joined: 20-September 08


Dream Kudos: 1075

Re: Searching an array

Posted 17 April 2009 - 08:55 PM

View Postjanotte, on 17 Apr, 2009 - 06:20 PM, said:

Absolutely agree with every point!

If you haven't already, have you considered a tutorial expanding this out a bit?

It would be a good resource for students that we could point them at.


Thanks for the generous comments Janotte ... I may soon not have much access to a PC ... but I'll see ...

Shalom,
David
Was This Post Helpful? 0
  • +
  • -

#12 David W  Icon User is offline

  • DIC supporter
  • Icon

Reputation: 130
  • Posts: 1,013
  • Joined: 20-September 08


Dream Kudos: 1075

Re: Searching an array

Posted 19 April 2009 - 05:07 AM

View Postjanotte, on 17 Apr, 2009 - 06:20 PM, said:

Absolutely agree with every point!

If you haven't already, have you considered a tutorial expanding this out a bit?

It would be a good resource for students that we could point them at.



Ok, here is a reference link for a start ... near the bottom of the page at this link ...

http://developers-he...260.html#msg260

Please feel free to link to it ...

For about 2 years now, beginning with Beginning Computer Programming (with HLA) ... that highly regarded HLA (High Level Assembly) language (by prof. Randall Hyde of HLA fame), I have been developing a series of free on-line helps for CS students. As suggested in the previous post in this thread, I may be approaching the end ... (and so may we all ... but it's just the end of this age only ... and soon ... but after a very trying predicted 3.5 years ... the true Messiah will re-appear ... just like He promised ... about 2000 years ago ... It seems the anti-Messiah is about to step out onto the world stage to solve the Global Economic Problem ... with his long and well pre-planned Global Economy Salvation ... perhaps (mostly) cashless ... and perhaps via a chip in the right hand or forehead along the lines of what was foretold by the Apostle John about 1900 years ago... (You can read John's well written record ... in Revelation chapter 13 in the Holy Bible.)

Anyways ... I think the DIC site is well endowed with very talented and often very generous helpers ... and I hope that it continues to be a very special place for CS students to be encouraged and if necessary ... to get put onto the right track.

Shalom,

David
http://developers-he.../index.p...opic,127.0.html
Was This Post Helpful? 0
  • +
  • -

#13 Lattimer24  Icon User is offline

  • New D.I.C Head
  • Pip

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 29-October 08


Dream Kudos: 0

Re: Searching an array

Posted 19 April 2009 - 10:32 AM

David W,

Thank you again for your helpful insights with my question. I do find it difficult at times to author the proper comments for my coding and your example did clarify what good commenting guidelines should be. Also, the other good practices you mentioned just aren't taught at my school. Granted I am currently attending a community college, I will be starting a Masters program next month and would like to develop concrete professional business practices that will allow me to stand out when applying for future careers. Thank you again for your help and take care.

Lattimer
Was This Post Helpful? 0
  • +
  • -



Fast Reply

  

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users