Hello! My name is Page, and I am still in the process of becoming a more seasoned programmer. I am trying to get a .txt file with first names in it to be sorted after I read the file and input it to a array from a function. Now I know how to sort integers but I am having a extremely hard time fully understanding how to sort a string array.
I also need some direction with searching the array.... I know its very choppy right now (My code). I just am working on getting somewhat of a rough draft before I start to really debug. If possible can I get an example or direction on how to sort and search for two names, and be able to see how many times the names that the user input were found. I have also attached the .txt I will be working with.

Thank you very much.

// FILE: P1_NameSearch_Functions.cpp (Function File)
// This program will cover strings, arrays, file I/O, pointers/references.
// OBJECTIVE: Read a file of first names and search fro names entered by the user. 

#include <iostream>				// Needed for cin and cout
#include <string>				// Needed for string values
#include <fstream>              // Reading/Writing from file requires this standard library.

using namespace std;

// For easier access #define is used for file names
#define FILE_IN "FirstNames.txt"
#define FILE_OUT "FirstNames_Summary.txt"

void Objective_screen(string *name)
	{
	// Declared variables
	char ENTER;

	// Greeting and introduction to the program
	// Ask for user name and return string
	cout << "\n Hello! \n";
	cout << "\n WELCOME TO THE C++ SEARCH FOR NAMES PROGRAM \n";
	cout << "\n My name is Page, and I will go over the main "
		 << "\n objective and instructions for the C++ SEARCH "
		 << "\n FOR NAMES PROGRAM! \n";
	cout << "\n If you do not mind I have a question...";
	cout << "\n What is your full name? ";
	getline(cin, *name);
	
	cout << "\n Nice to meet you " << *name << ". \n";
	cout << "\n This program uses input/output data files for the information "
		 << "\n and the array. The array is used for data of the same type "
		 << "\n (variables) that is best grouped together. \n";
	
	cout << "\n After the data file has been accessed the names will be sorted "
		 << "\n as specified later in the program. \n";
	cout << "\n LET'S START! Hit ENTER to continue... \n";
	// Waits for user's input before program continues
	cin.get(ENTER);
	}

bool ReadFile(string names[], int *pTotal)
{
	/* This is the function that will fill the name[] array,
	   after the data file has been successfully located.*/

	// Declared Variables
	string filename = "FirstNames.txt";

	/* Uses the 'open' member function of the ifstream object to
	   open a file for reading. */
	ifstream FirstNamesInput;

	/* Since the file name is a string the 'open' element needs a char[].
	   So, it is nessecary to us the c_str() function to give the string
	   in proper char[] format. */
	FirstNamesInput.open(filename.c_str()); 

    // Here we must make sure that the file was opened
	if(!FirstNamesInput)
	{
		cout << "\n Opps! ERROR... Can't Find " << filename;
		cout << "\n =============================================== \n " << endl;
		exit(1);
		// Returns the false value (or failure) in Boolean form
		return false;
	}
	
	/* Needed to make sure I count the words/names in the .txt file.
	   The *pIndex is used as a reference parameter to located the
	   total number of strings in the file as well as the first element. */
	else
	{
		FirstNamesInput >> *pTotal;
		cout << "\n There are a total of " << *pTotal << " names in the file. " << endl;
	}
	// Collecting data for the array and filling the names into the array.
	for(int i = 1; i < *pTotal + 1; ++i)
	{
		FirstNamesInput >> names[i-1];
	}
		// Returns the true value (or success) in boolean form
		return true;
}

void bubbleSort(string names[], int *pTotal)
{
	// Declared Variables
	// This is used for a place holder of a temporary string (name).
	string temp;

	/* This loop compares the available adjacent values, and moves the values around
	   until they are in the correct order. In other word... it will help to properly
	   sort the names in this situation. */
	for(int i = 0; i < *pTotal - 1; ++i)						// This is the first of dual (nested) loop
	{
		bool swapped = false;
		for(int j = 1; j < *pTotal; ++j)						// This is the second of dual (nested) loop
		{
			/* This is used to determine if the specified array 
			   element [j - 1] is larger than [j]. */
			if(names[j] > names[j + 1])
			{
				temp = names[j];								// Temporary holds value of [j]
				names[j] = names[j - 1];						// Array element is assigned the value of [j - 1]
				names[j - 1] = temp;							// Element [j - 1] is replaced by temporary
				swapped = true;
			}
		}
		if (!swapped) break;									// The names are all sorted.
	}
}

void AskForTwoNames(string *pUserInput)
{
	// This function will ask the user to input two first names of their choice.
	cout << "\n Please enter in two first names, in CAPS, separated by a space:      " << endl;
	getline(cin, *pUserInput);
	
	// Makes sure that the user enters two names and not nothing.
	if(*pUserInput.length() == 0) 
	{
		cout << "\n Please enter in two first names, again:      " << endl;
		getline(cin, *pUserInput);
		continue;
	}
}

bool SearchNames(string names[], int *pTotal, *pUserInput)
{

}
// FILE: P1_NameSearch_Header.h (Header file/prototype)
// This program will cover strings, arrays, file I/O, pointers/references.
// OBJECTIVE: Read a file of first names and search fro names entered by the user. 

#include <iostream>				// Needed for cin and cout
#include <string>				// Needed for string values

using namespace std;

/* This is the function that will be responsible for displaying the program's
   introduction, main objective, rules, and a brief user greeting. */
void Objective_screen(string *name);

/* This is the function that will return a Boolean value, which is checked
   in main(). If the specified file can't be located, a message will be
   displayed to inform user, and the program with exit. If the file is found,
   the names[] array will be filled, and the total number of names that were
   read are returned to the main() function. */
bool ReadFile(string names[], int *pTotal);

/* This function uses a modified version of the 'bubble sort' to sort
   the names from the data file in a fashion that is requested. */
void bubbleSort(string names[], int *pTotal);

/* This function will use pointers and or references to obtain two names
   from the functions and then pass the specified names. */
void AskForTwoNames(string *pUserInput);

/* The array, total number of names, and the user's specified selection 
   of two names is passed to this function (SearchNames()). Then it
   will pass the results (whether the names were found and how many
   times the names occurred). */
bool SearchNames(string names[], int *pTotal, *pUserInput);
// FILE: P1_NameSearch_Driver.cpp (Drive/main)
// This program will cover strings, arrays, file I/O, pointers/references.
// OBJECTIVE: Read a file of first names and search fro names entered by the user. 

#include <iostream>				// Needed for cin and cout
#include <string>				// Needed for string values
#include <fstream>              // Reading/Writing from file requires this standard library.

using namespace std;

#include "P1_NameSearch_Functions.cpp"

int main()
{
	// Declared Variables
	string names[800];
	string pUserInput;
	int pTotal;
	
	// Function for the Objective Screen
	Objective_screen(&name);

	cout << "\n Data Contained In \"FirstNames.txt\" \n";

	// Call ReadFile() function to read data (names) into names[];
	// The ReadFile() function will return a false if the file can't be found.
	bool ok = ReadFile(names, &pTotal);

	// This loop is to make sure that the data file was opened successfully.
	if(ok == false)
	{
		cout << "\n Opps! ERROR... Can't Continue Working, NO DATA! ";
		cout << "\n =============================================== \n " << endl;
		// Returned false, no file, and the program terminates.
		exit(1);
	}
	
	/* This calls the bubbleSort() function from where the array names[]
	   is read and sorted via its values. */
	void bubbleSort(names, &pTotal);

	/* The function called AskForTwoNames() will use pointer and or 
	   references to obtain two names from the functions. */
	void AskForTwoNames(&pUserInput);


	// After everything nessecary is complete, the file can be closed.
	Input.close();

	return 0;

}

Some general things because this doesn't even compile (which I think you implied):

Lines 40 and 44 of your driver program, you don't need to put the return type in front of them when calling your methods in main().

Wrap your header file in:

#ifndef P1_NAMESEARCH_H
#define P1_NAMESEARCH_H

//the rest of your header here

#endif //at the very bottom

and don't include the cpp file in tho other one, instead include your header file in both the functions.cpp and the driver.cpp.

In your header, just pick something for this last parameter to this function (you can always change it later) so it's working to the point that you can begin to play around with your program to test changes. bool SearchNames(string names[], int *pTotal, *pUserInput); I know this is not exactly what you wanted but it will make it easier for someone to help you then they don't have to go wading through a bunch of errors.

>>direction on how to sort

In line 103 you compare index j and j + i but lines 106 and 107 you are swapping indexes j and j - 1. Why are you using different indexes?

Either use j + 1 in all three lines with 0 <= j < *pTotal - 1.

Or, if you must start j at 1 then use index j - 1 in all three lines but do something like:

if(names[j - 1] > names[j])
{
    temp = names[j - 1];
    names[j - 1] = names[j];
    names[j] = temp;
}

Note that in either case the element with the larger value ends up with the index of the larger value

Thank you, I appreciate it. Sometimes the smallest most simple syntax errors are the ones that discourage us the most.

Oh gezzz, I didn't see that at all, thank you. Like I had mentioned I was kinda confused on that modified bubble sort. Thanks once again.

Hello How are you guys? I have another question....
I got the program to run and fixed some of the errors, but I noticed it is not counting the names from the text file properly. I am not sure if it is a initializing error or logic? Also I have looked everywhere for how to properly search and sort the names from the text file, and no luck. I have tried to set up to the sort with some help from you guys, but its not working. Also I having no Idea how to go about setting up the searching function. If possible can you guild me in the right direction. Can you show me an example of how to go about it? I just haven't found a proper example to help me get it started. Thank you very much.
I will post the files for viewing again.


Header

// FILE: P1_NameSearch_Header.h
// This program will cover strings, arrays, file I/O, pointers/references.
// OBJECTIVE: Read a file of first names and search fro names entered by the user. 

#include <iostream>				// Needed for cin and cout
#include <string>				// Needed for string values

using namespace std;

/* This is the function that will be responsible for displaying the program's
   introduction, main objective, rules, and a brief user greeting. */
void Objective_screen(string *pName);

/* This is the function that will return a Boolean value, which is checked
   in main(). If the specified file can't be located, a message will be
   displayed to inform user, and the program with exit. If the file is found,
   the names[] array will be filled, and the total number of names that were
   read are returned to the main() function. */
bool ReadFile(string names[], int &rTotal);

/* This function uses a modified version of the 'bubble sort' to sort
   the names from the data file in a fashion that is requested. */
void bubbleSort(string names[], int &rTotal);

/* This function will use pointers and or references to obtain two names
   from the functions and then pass the specified names. */
void AskForTwoNames(string &rUserInput);

/* The array, total number of names, and the user's specified selection 
   of two names is passed to this function (SearchNames()). Then it
   will pass the results (whether the names were found and how many
   times the names occurred). */
void SearchNames(string names[], int &rTotal, string &rUserInput);

/* The WriteOutput() function takes the values (User Input) that was 
   passed to the function, and displays the results as well as outputs
   the results to the specified output file. The output file will
   serve as a brief summary for the user; if they desire to open it
   and read the information. */
bool WriteOutput(string *pName, string names[], int &rTotal, string &rUserInput);

Function/Prototype

// FILE: P1_NameSearch_Functions.cpp
// This program will cover strings, arrays, file I/O, pointers/references.
// OBJECTIVE: Read a file of first names and search fro names entered by the user. 

#include <iostream>				// Needed for cin and cout
#include <string>				// Needed for string values
#include <fstream>              // Reading/Writing file requires this standard library.

using namespace std;

// For easier access #define is used for file names
#define FILE_IN "FirstNames.txt"
#define FILE_OUT "FirstNames_Summary.txt"

void Objective_screen(string *pName)
	{
	// Declared variables
	char ENTER;

	// Greeting and introduction to the program
	// Ask for user name and return string
	cout << "\n Hello! \n";
	cout << "\n Welcome! \n";
	cout << "\n THE C++ SEARCH FOR FIRST NAMES PROGRAM \n";
	cout << "\n My name is Page, and I will go over the main "
		 << "\n objective and instructions for the program. \n";
	cout << "\n If you do not mind I have a question...";
	cout << "\n What is your full name? ";
	getline(cin, *pName);
	
	cout << "\n Nice to meet you " << *pName << ". \n";
	cout << "\n This program uses input/output data files for the information "
		 << "\n and the array. The array is used for data of the same type "
		 << "\n (variables) that is best grouped together. \n";
	
	cout << "\n After the data file has been accessed the names will be sorted "
		 << "\n as specified later in the program. \n";
	cout << "\n LET'S START! Hit ENTER to continue... \n";
	// Waits for user's input before program continues
	cin.get(ENTER);
	}

bool ReadFile(string names[], int &rTotal)
{
	/* This is the function that will fill the name[] array,
	   after the data file has been successfully located.*/

	// Declared Variables
	string filename = "FirstNames.txt";

	/* Uses the 'open' member function of the ifstream object to
	   open a file for reading. */
	ifstream FirstNamesInput;

	/* Since the file name is a string the 'open' element needs a char[].
	   So, it is nessecary to us the c_str() function to give the string
	   in proper char[] format. */
	FirstNamesInput.open(filename.c_str()); 

    // Here we must make sure that the file was opened
	if(!FirstNamesInput)
	{
		cout << "\n Opps! ERROR... Can't Find " << filename;
		cout << "\n =============================================== \n " << endl;
		exit(1);
		// Returns the false value (or failure) in boolean form
		return false;
	}
	
	/* Needed to make sure I count the words/names in the .txt file.
	   The *pIndex is used as a reference parameter to located the
	   total number of strings in the file as well as the first element. */
	else
	{
		FirstNamesInput >> rTotal;
		cout << "\n There are a total of " << rTotal << " names in the file. " << endl;
	}
	// Collecting data for the array and filling the names into the array.
	for(int i = 1; i < rTotal + 1; ++i)
	{
		FirstNamesInput >> names[i-1];
	}
		// Returns the true value (or success) in boolean form
		return true;
}

void bubbleSort(string names[], int &rTotal)
{
	// Declared Variables
	// This is used for a place holder of a temporary string (name).
	string temp;

	/* This loop compares the availible adjacent values, and moves the values around
	   untill they are in the correct order. In other word... it will help to properly
	   sort the names in this situation. */
	
	// This is the first of dual (nested) loop
	for(int i = 0; i < rTotal - 1; ++i)							
	{
		bool swapped = false;
		
		// This is the second of dual (nested) loop
		for(int j = 1; j < rTotal; ++j)							
		{
			/* This is used to determine if the specified array 
			   element [j - 1] is larger than [j]. */
			if(names[j - 1] > names[j])
			{
				// Temp holds value of [j - 1]
				temp = names[j - 1];							
				// Array element is assigned the value of [j - 1]
				names[j - 1] = names[j];						
				// Element [j - 1] is replaced by temp
				names[j] = temp;								
			}
		}
	}
}
 
void AskForTwoNames(string &rUserInput)
{
	// This function will ask the user to input two first names of thier choice.
	cout << "\n ENTER two first names, In CAPS, seperated by a SPACE:      " << endl;
	getline(cin, rUserInput);
	cin.ignore();
	
	// Makes sure that the user enters two names and not nothing.
	//if(rUserInput.length() == 0) 
	//{
	//	cout << "\n Please enter in two first names, again:      " << endl;
	//	getline(cin, rUserInput);
	//}
}

void SearchNames(string names[], int &rTotal, string &rUserInput)
{
	cout << "\n TESTING FUNCTIONS! ";
}

bool WriteOutput(string *name, string names[], int &rTotal, string &rUserInput)
{
	// Declared Variables
	string filename = "FirstNames_Summary.txt";

	/* The WriteOutput() function recieves the values that were passed to them
	   as well as the users input for the search and displays them to the
	   screen. This file also shows the user the output file for the results
	   and or summary of the outcome of the program. */
	
	// This will make FirstNamesOutput cast as cin or cout
	ofstream FirstNamesOutput;										
	// Needed to open output file
	FirstNamesOutput.open(filename.c_str());								

	// This is used to test if the specified output file exists
	if(!FirstNamesOutput)
	{
		// Let user know if there was an error and/or no output file was found
		cout << "\n Opps! ERROR... Can't Find " << filename;
		cout << "\n =============================================== \n " << endl;
		exit(1);
		
		// Returns the false value (or failure) in boolean form
		return false;
	}
	else
	{
		// Let user know that the program has successfully found and identified output file
		cout << "\n CONGRATULATIONS! C++ SEARCH FOR FIRST NAMES PROGRAM FOUND "
			 << "\n THE OUTPUT FILE CALLED: ------!>    " << FILE_OUT << "\n";

	FirstNamesOutput << "\n ----------!>  RESULTS  <!---------- \n";
	FirstNamesOutput << "\n User's Name:	" << *name;	
	FirstNamesOutput << "\n User Input:		" << rUserInput;  
	FirstNamesOutput << "\n ";
	}

	cout << "\n C++ SEARCH FOR FIRST NAMES PROGRAM is finished writting data. ";
	cout << "\n To view the results please open the file named " << FILE_OUT;
	cout << "\n The file named " << FILE_OUT << " can be found in the "
		 << "\n project folder. " << endl; 

	// Reading and writing complete, closing file.
	FirstNamesOutput.close();
	
	return true;
}
// END OF THE C++ SEARCH FOR FIRST NAMES PROGRAM

Driver

// FILE: P1_NameSearch_Driver.cpp
// This program will cover strings, arrays, file I/O, pointers/references.
// OBJECTIVE: Read a file of first names and search fro names entered by the user. 

#include <iostream>				// Needed for cin and cout
#include <string>				// Needed for string values
#include <fstream>              // Reading/Writing file requires this standard library.

using namespace std;

#include "P1_NameSearch_Header.h"

int main()
{
	// Declared Variables
	string names[800], pName, rUserInput, answer;
	int rTotal;
	
	// Function for the Objective Screen
	Objective_screen(&pName);

	cout << "\n Data Contained In \"FirstNames.txt\" \n";

	do {

	// Call ReadFile() function to read data (names) into names[];
	// The ReadFile() function will return a false if the file can't be found.
	bool ok = ReadFile(names, rTotal);

	// This loop is to make sure that the data file was opened successfully.
	if(ok == false)
	{
		cout << "\n Opps! ERROR... Can't Continue Working, NO DATA! ";
		cout << "\n =============================================== \n " << endl;
		// Returned false, no file, and the program terminates.
		exit(1);
	}
	
	/* This calls the bubbleSort() function from where the array names[]
	   is read and sorted via its values. */
	bubbleSort(names, rTotal);

	/* The function called AskForTwoNames() will use pointer and or 
	   references to obtain two names from the functions. */
	AskForTwoNames(rUserInput);

	SearchNames(names, rTotal, rUserInput);

	bool result = WriteOutput(&pName, names, rTotal, rUserInput);
	
	// Ask the user if they would like to search names again.
	cout << "\n Would you like to search again? "
		 << "\n PLEASE TYPE ANSWER IN CAPS! (YES or NO)? \n";
	cout << "\n Please make sure to hit the ENTER key TWICE! \n\n";
	getline(cin, answer);
	cin.ignore();

	}while (answer == "YES");

	return 0;
}

Sorry for the excessive length, and once again I really appreciate the help. This method for help really makes the information sink in ten times more efficient.

*Page*

In your driver you can change:

bool ok = ReadFile(names, rTotal);

	// This loop is to make sure that the data file was opened successfully.
	if(ok == false)

--to--
if(!ReadFile(names, rTotal))  //not overly compact but helps someone 
                                 //see the two steps in one

The main problem hampering you at the moment is in 73-76 of your "Functions.cpp" file. Line 73 is attempting to read the first line of the file (a name) into a character variable. That name value is being interpreted as 7536754 What you want to do is put in a while loop:

int rTotal = 0;
while(FirstNamesInput >> names[rTotal])
        rTotal++;

That will give you an accurate count.
Just a suggestion: you don't have to use this index i - 1 stuff, arrays are all 0 based, it hasn't changed in 40 some odd years, probably won't.

Another hint: when you're in this debugging stage knock your list down to 10 or so names just so if you have to step through it 100 times it won't be as much.

Another hint. Don't try to debug the whole program at once. Write a function or an action or even just declare variables and recompile, rerun. It's much easier to debug a little bit at a time.

Remember that rTotal is declared in main() and sent to ReadFile by reference so don't be lazy and just copy/past jonsca's last snippet into your program. Use the snippet to do what you need to do in the context of your program.

commented: Good catch! +1

Whoops that was done on autopilot. Thanks Lerner. But do set it to zero before your loop.

Thank you, I appreciate it. I try that and see.

I just have a quick question... I want to clarify something, just so I don't imprint something in my brain in the wrong context:

do {
		// Call ReadFile() function to read data (names) into names[];
		// The ReadFile() function will return a false if the file can't be found.
		if(!ReadFile(names, rTotal))
		{
                 // So get rid of this below 
		// bool ok = ReadFile(names, rTotal);

		// This loop is to make sure that the data file was opened successfully.
                // and this one too
		//if(ok == false)
	
		cout << "\n Opps! ERROR... Can't Continue Working, NO DATA! ";
		cout << "\n =============================================== \n " << endl;
		// Returned false, no file, and the program terminates.
		exit(1);
		}

Now this will take care of the Boolean statement and if statement, and complete both of those in one summed up code:

if(!ReadFile(names, rTotal))

Correct?

Now it dies right after it opens the file...... What did I do wrong now.....

Ok I got everything functioning properly, I just haven't been able to get the search to work properly. What should I do? Is there a specific method I should use?
I will attach the correct code so far....

Now this will take care of the Boolean statement and if statement, and complete both of those in one summed up code:
Correct?

Correct. There's never a need to do if(xyz == false), you just do if(!xyz), since if xyz is false, !xyz will be true and if(true) will follow the code after the if statement.

Since your method returns a boolean you get it all done in one step. It doesn't always pay to cram everything down into one but in this case IMHO, most people prefer to see it this way then to have to go back and check.

Ok I got everything functioning properly, I just haven't been able to get the search to work properly. What should I do? Is there a specific method I should use?

You need to split the string rUserInput into name one and name two, you can do that with the string functions themselves (hint: substr). Next look up binary search (http://en.wikipedia.org/wiki/Binary_search_algorithm).

Since you've sorted your names list already you more than likely need a binary search. You can start at the middle of the list and see if the name you are searching for is "higher" or "lower" (with std::string you can use the < > == operators). If it's in the upper half, go to the middle of that part of the list and see if it's in the higher portion of the upper half or the lower portion of the upper half , etc., keep splitting it until you find the element or until you get to 1 non-matching element (at that point you haven't matched it).

|                             x|                y|        z|         |
(so is it less than or greater than element x?  say greater
 go to y
is it less than or greater than y? greater
go to z

Oh I See! I thought working out a logic statement in order to find the desired names would be rocket science, now that you explain it like that its not so bad. Thank you!

Okay, I read several different things on the substr and from what I read, I will show you what I got from it. Will you let me know if I am right, or not even anywhere close? Here's the function from my code that asks the user to input the two names by a space:

void AskForTwoNames(string &rUserInput)
{
	// Declared Variables
	string NameONE, NameTWO;

	// This function will ask the user to input two first names of their choice.
	cout << "\n ENTER two first names, In CAPS, seperated by a SPACE:      " << endl;
	getline(cin, NameONE, NameTWO);
	cin.ignore();

	rUserInput = NameONE + NameTWO;
}

or would I do this?

void AskForTwoNames(string &rUserInput)
{
	// Declared Variables
	string NameONE, NameTWO;

	// This function will ask the user to input two first names of their choice.
	cout << "\n ENTER two first names, In CAPS, seperated by a SPACE:      " << endl;
	getline(cin, NameONE, NameTWO);
	cin.ignore();

       rUserInput = strcat(NameONE, NameTWO);
	
}

Or do I do this? I am still kinda confused, every example I look at is not explained very well, thus leaving me guessing.

void AskForTwoNames(string &rUserInput, string &rNameONE, string &rNameTWO)
{
	// This function will ask the user to input two first names of their choice.
	cout << "\n ENTER two first names, In CAPS, separated by a SPACE:      " << endl;
	getline(cin, rUserInput);
	cin.ignore();
	
	rNameONE = rUserInput.substr(15);
	rNameTWO = rUserInput.substr(15);

}

Or do I do this?

Well, your last one was closest. If you are permitted to pass additional parameters I would go with:

void AskForTwoNames(string &rNameONE, string &rNameTWO)
{
            cout <<"Enter name 1: ";
            cin >> NameONE; //or getline but don't mix cin/getline
             //if you do cin then getline you'll have extra chars in the stream
            //which you could sweep up with an ignore statement like
             //you have but it's extra hassle
            cout <<"\nEnter name2";
            cin >> NameTWO; //or getline but see above
}

That way you're not taking them in one at a time and making one string only to split it again in your search step (unless like I said if you were restricted to passing 1 parameter only).

Just for comparison's sake (and to point out the substr):
What I did (assuming the you couldn't pass in the two strings) was within your WriteOutput:

int index = rUserInput.find(" ");
	string name1 = rUserInput.substr(0,index-1);
	string name2 = rUserInput.substr(index+1);

find(" ") returns the zero-based index of the first space in your string, then I took the substring from 0 of length index -1 (so in the string "Adam Smith" the space would be found at index 4, so I'd take 4 chars starting from zero) and then took another substring from the character after the space until the end (S is at position 5 to the end -- so if you took substr(0) you'd end up with your whole string again). See this for a good example.

You've done a great job with this, so never feel like your time "experimenting" is in vain :)

Searching and sorting algorithms are topics that probably take up whole courses or books. Use what you have or can work up quickly. Simple linear searching works well for many programs, particularly if the number of items to search isn't too big. Binary searches and other searches are useful if you have large numbers of items to search. A linear search of an array of objects of type T can be as simple as:

const int max = whatever
T array[MAX] = something here
T target = desired value
for(int i = 0; i < max; ++i)
   if(array[i] == target)
      do something

Hello!
I wanted to thank you guys once again for all the help you have given me. I am understanding the algorithms a lot better, but I am still just slightly stuck one little thing involving the binary search.
I have a just one more question... question regarding the set up of my binary search. I would like to search for the two names the user inputs and let the user know how many times I found each specified first name. I then have the results sent to the last function, from which I display the results of the search. I have debugged the program and set everything up ( I thinks it okay? I am fully open for constructive criticism regarding my coding or techniques that I have implemented. I would like to learn as much as possible.), but I fear that since I am sorta new to C++ that my format for the search could be set up better. Also I have set it up so that the first name is searched but I have not quite figured out how to get the second name or the results sent. For the results I mean whether or not the names were located and how many times the particular name was found.
Once again I appreciate all the help I have received, the way the help was offered was great. I was able to gather the knowledge and use the help to write the code in a matter that helped me understand it better.

I will attach the .txt files, my program files ect.....

Here is my header file:

// FILE: P1_NameSearch_Functions.h
// This program will cover strings, arrays, file I/O, pointers/references.
// OBJECTIVE: Read first names data & search for the corresponding user input. 

#include <string>				// Needed for string values

using namespace std;

/* This is the function that will be responsible for displaying the program's
   introduction, main objective, rules, and a brief user greeting. */
void Objective_screen(string *pName);

/* This is the function that will return a Boolean value, which is checked
   in main(). If the specified file can't be located, a message will be
   displayed to inform user, and the program with exit. If the file is found,
   the names[] array will be filled, and the total number of names that were
   read are returned to the main() function. */
bool ReadFile(string names[], int &rIndex);

/* This function uses a modified version of the 'bubble sort' to sort
   the names from the data file in a fashion that is requested. */
void bubbleSort(string names[], int &rIndex);

/* This function will use pointers and or references to obtain two names
   from the functions and then pass the specified names. */
void AskForTwoNames(string &rNameONE, string &rNameTWO);

/* The array, total number of names, and the user's specified selection 
   of two names is passed to this function (SearchNames()). Then it
   will pass the results (whether the names were found and how many
   times the names occurred). */
void SearchNames(string names[], int &rIndex, string &rNameONE, string &rNameTWO,
				 int &rCount_NameONE, int &rCount_NameTWO);

/* The WriteOutput() function takes the values (User Input) that was 
   passed to the function, and displays the results as well as outputs
   the results to the specified output file. The output file will
   serve as a brief summary for the user; if they desire to open it
   and read the information. */
bool WriteOutput(string *pName, string names[], int &rIndex, string &rNameONE, 
				 string &rNameTWO, int &rCount_NameONE, int &rCount_NameTWO);

Here is the functions:

// FILE: P1_NameSearch_Functions.cpp
// This program will cover strings, arrays, file I/O, pointers/references.
// OBJECTIVE: Read first names data & search for the corresponding user input. 

#include <iostream>				// Needed for cin and cout
#include <string>				// Needed for string values
#include <fstream>              // Reading/Writing file requires this standard library.
#include <string.h>

using namespace std;

// For easier access #define is used for file names
#define FILE_IN "FirstNames.txt"
#define FILE_OUT "FirstNames_Summary.txt"

void Objective_screen(string *pName)
	{
	// Declared variables
	char ENTER;

	// Greeting and introduction to the program
	// Ask for user name and return string
	cout << "\n     AUTHOR:		SELF EXPLANATORY ";
	cout << "\n     E-MAIL:		SELF EXPLANATORY ";
	cout << "\n      CLASS:		CIS 2275 ";
	cout << "\n ASSIGNMENT:		SELF EXPLANATORY \n";
	cout << "\n -------------------------------------------------------------- ";
	cout << "\n       C++ U.S. CENSUS DATA MOST COMMON FIRST NAME SEARCH ";
	cout << "\n -------------------------------------------------------------- ";

	cout << "\n                  HELLO!                      ";
	cout << "\n My name is Page, and I will go over the main "
		 << "\n objective and instructions for my program. \n";
	cout << "\n If you do not mind, I have a question...";
	cout << "\n What is your full name? ";
	getline(cin, *pName);
	
	cout << "\n Nice to meet you " << *pName << ". \n";
	cout << "\n This program will make use of input/output files for the "
		 << "\n census data. This program will search the census data for "
		 << "\n user specified occurences of popular first names. ";
	cout << "\n This program will visually narrate the steps that this "
		 << "\n program goes through to achieve the final results. \n";

	cout << "\n TO START THE PROGRAM HIT THE ENTER TO BEGIN... \n";
	// Waits for user's input before program continues
	cin.get(ENTER);
}

bool ReadFile(string names[], int &rIndex)
{
	/* This is the function that will fill the names[] array,
	   after the data file has been successfully located.*/

	// Declared Variables
	string filename = "FirstNames.txt";
	
	/* Uses the 'open' member function of the ifstream object to
	   open a file for reading/input. */
	ifstream FirstNamesInput;

	/* Since the file name is a string the 'open' element needs a char[].
	   So, it is nessecary to us the c_str() function to give the string
	   in proper char[] format. */
	FirstNamesInput.open(filename.c_str()); 

    // Here we must make sure that the file was opened
	if(!FirstNamesInput)
	{
		cout << "\n		Opps! Error... Cannot Locate \"" << FILE_IN << "\"";
		cout << "\n ----------------------------------------------------- \n " << endl;
		exit(1);
		// Returns the false value (or failure) in boolean form
		return false;
	}
	
	/* Needed to make sure I count the words/names in the .txt file.
	   The &rIndex is used as a reference parameter to located the
	   total number of strings in the file as well as the first element. */
		rIndex = 0;
        
		while(FirstNamesInput >> names[rIndex])
        ++rIndex;
		cout << "\n There are a total of " << rIndex << " names in the file. " << endl;
	
		// Collecting data for the array and filling the names into the array.
	
		// Returns the true value (or success) in boolean form
		return true;
}

void bubbleSort(string names[], int &rIndex)
{
	// Declared Variables
	// This is used for a place holder of a temporary string (name).
	string temp;

	/* This loop compares the availible adjacent values, and moves the values around
	   untill they are in the correct order. In other word... it will help to properly
	   sort the names in this situation. */
	
	// This is the first of dual (nested) loops
	for(int i = 0; i < rIndex - 1; ++i)							
	{
		bool swapped = false;
		
		// This is the second of dual (nested) loop
		for(int j = 1; j < rIndex; ++j)							
		{
			/* This is used to determine if the specified array 
			   element [j - 1] is larger than [j]. */
			if(names[j - 1] > names[j])
			{
				// Temp holds value of [j - 1]
				temp = names[j - 1];							
				// Array element is assigned the value of [j - 1]
				names[j - 1] = names[j];						
				// Element [j - 1] is replaced by temp
				names[j] = temp;								
			}
		}
	}
}
 
void AskForTwoNames(string &rNameONE, string &rNameTWO)
{
	// This function will ask the user to input two first names of thier choice.
	cout << "\n Enter in two first names, in CAPS, seperated by a space:      ";
	cin  >> rNameONE >> rNameTWO;
	
	// This was to be used if I had to collect both names into one variable.
    // int index = rUserInput.find(" ");
    // rNameONE = rUserInput.substr(0,index-1);
    // rNameTWO = rUserInput.substr(index+1);
}

void SearchNames(string names[], int &rIndex, string &rNameONE, string &rNameTWO, 
				 int &rCount_NameONE, int &rCount_NameTWO)
{

	/* This is a standard Binary Search Alogorithm, slightly modified to be more
	   efficient with my particular assingment. This search takes a sorted array
	   of values, names, or character and takes the total amount or Index. Then
	   the total amount of items is saved, and the high and low values are added
	   and divided by 2. This value will be the middle and so fourth the idea. */
	
	// Basic Binary Search Alogorithm

	/********** Declared Variables **********/

	// When ever low and high cross the process has ended
	// HigherBound will begin by equaling the last index.
	int HigherBound = rIndex - 1;
	// LowerBound will begin in the very front of the Array
	int LowerBound = 0;
	// This will hold the average of High and Low
	int MiddleBound = 0;
	// Use as a simple boolean
	int Found = 0;
	// This will hold how many time we have looped
	int Permutation = 0;

	// Initialize Counter
	rCount_NameONE = 0;
	rCount_NameTWO = 0;
	
	// Start of Binary Search
	while ((LowerBound <= HigherBound) && (Found == 0))
	{
		MiddleBound = (LowerBound + HigherBound) / 2;			
		
		if(names[MiddleBound] == rNameONE)
		{
			Found = 1;
			++rCount_NameONE;
		}
		else if(names[MiddleBound] < rNameONE)
		{
			LowerBound = MiddleBound + 1;
		}
		else
		{
			HigherBound = MiddleBound - 1;
		}

	 // View whats going on in this loop    
	 // This is just temporary to see if successfull
	 // If works properly I will send results to WriteOutput(); function.
	 cout << "\n             The Search Was Run: " << Permutation << " Times. ";
	 cout << "\n The Index's Higher-Bound Value: " << HigherBound;
	 cout << "\n The Index's Middle-Bound Value: " << MiddleBound;
	 cout << "\n  The Index's Lower-Bound Value: " << LowerBound << endl;
	 // This value holds the amount of loops (How many cycles)
	 Permutation++;						
	}
	if(Found == 1)
	{
		cout << rNameONE << " Is In The List, " << rCount_NameONE << " Times. ";
		cin.get();
	}
	else 
	{
		cout << rNameONE << " Is Not In The List. ";
		cin.get();
	}										
		cin.get();
}										

bool WriteOutput(string *pName, string names[], int &rIndex, string &rNameONE, 
				 string &rNameTWO, int &rCount_NameONE, int &rCount_NameTWO)
{
	/* The WriteOutput() function recieves the values that were passed to them
	   as well as the users input for the search and displays them to the
	   screen. This file also shows the user the output file for the results
	   and or summary of the outcome of the program. */
	
	// Declared Variables
	string filename = "FirstNames_Summary.txt";
	
	// This will make FirstNamesOutput cast as cin or cout
	ofstream FirstNamesOutput;										
	// Needed to open output file
	FirstNamesOutput.open(filename.c_str());								

	// This is used to test if the specified output file exists
	if(!FirstNamesOutput)
	{
		// Let user know if there was an error and/or no output file was found
		cout << "\n		Opps! Error... Cannot Locate \"" << FILE_OUT << "\"";
		cout << "\n ----------------------------------------------------- \n " << endl;
		exit(1);
		
		// Returns the false value (or failure) in boolean form
		return false;
	}
	else
	{
		// Let user know that the program has successfully found and identified output file
		cout << "\n CONGRATULATIONS! ";
		cout << "\n THE C++ U.S. CENSUS DATA MOST COMMON FIRST NAME SEARCH "
			 << "\n Has Located The Data Output File! ";
	
		FirstNamesOutput << "\n         AUTHOR:		SELF EXPLANATORY ";
		FirstNamesOutput << "\n          CLASS:		CIS 2275 ";
		FirstNamesOutput << "\n     ASSIGNMENT:		SELF EXPLANATORY \n";
		FirstNamesOutput << "\n -------------------------------------------------------------- ";
		FirstNamesOutput << "\n       C++ U.S. CENSUS DATA MOST COMMON FIRST NAME SEARCH ";
		FirstNamesOutput << "\n -------------------------------------------------------------- \n";
		FirstNamesOutput << "\n ------------RESULTS------------ \n";
		FirstNamesOutput << "\n    USER'S NAME:	    " << *pName;	
		FirstNamesOutput << "\n   USER'S INPUT:		" << rNameONE << "    " << rNameTWO;  
		FirstNamesOutput << "\n SEARCH OUTCOME:     ";
	}

	cout << "\n To view program outcome/results open the following: \"" << FILE_OUT << "\"";

	// Reading and writing complete, closing file.
	FirstNamesOutput.close();
	
	return true;
}
// END OF C++ U.S. CENSUS DATA MOST COMMON FIRST NAME SEARCH

Here is the driver:

// FILE: P1_NameSearch_Driver.cpp
// This program will cover strings, arrays, file I/O, pointers/references.
// OBJECTIVE: Read first names data & search for the corresponding user input. 

#include <iostream>				// Needed for cin and cout
#include <string>				// Needed for string values
#include <fstream>              // Reading/Writing file requires this standard library.

using namespace std;

#include "P1_NameSearch_Functions.h"

int main()
{
	// Declared Variables
		string names[800], pName, rNameONE, rNameTWO, answer;
		int rIndex, rCount_NameONE, rCount_NameTWO;
	
		// Function for the Objective Screen
		Objective_screen(&pName);

		cout << "\n Data Contained In \"FirstNames.txt\" \n";
	do {
		
		// Call ReadFile() function to read data (names) into names[];
		// The ReadFile() function will return a false if the file can't be found.
		if(!ReadFile(names, rIndex))
			
		/* This calls the bubbleSort() function from where the array names[]
		   is read and sorted via its values. */
		bubbleSort(names, rIndex);

		/* The function called AskForTwoNames() will use pointer and or 
		   references to obtain two names from the functions. */
		AskForTwoNames(rNameONE, rNameTWO);

		
		SearchNames(names, rIndex, rNameONE, rNameTWO, rCount_NameONE, 
								 rCount_NameTWO);
		
		bool ok = WriteOutput(&pName, names, rIndex, rNameONE, rNameTWO,
								  rCount_NameONE, rCount_NameTWO);
		
		// Ask the user if they would like to search names again.
		cout << "\n Would you like to search again? "
			 << "\n Please type answer in CAPS! (YES or NO)? ";
		cout << "\n Please hit the enter key twice! \n\n";
		getline(cin, answer);
		
		}while (answer == "YES");

		return 0;
}

I will attach the .txt file that contains the names just in case. I am pretty sure you guys have my code about 50 times.... :), but I will leave out the "summary file", it is basically self explanatory.

Thank you,


Page

Iam facing linker problems in this program
during compling..help me

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.