Hello! My name is Page, and I am having problems figuring out how to read a name for example like; SMITH, JOHN in a string array. From there I would like to find the space and read the last name into a vector and the first name into another vector. From there I would like to search for the users specified input and return how many I have found (It can also include a name such as JOHNSTON, if the user was searching for JOHN, or JOHN JOHNSTON would return 2 JOHN's) Thank you I appreciate it. I am having a hard time with the strings.
Here's my code:

Header File

//   CLASS:		CIS 2275 C++ II
// PROGRAM:		Program #2-A (Revision)  |  C++ 10K NAME SEARCH
//  E-MAIL:		ppotter03@inbox.com
//    FILE:		P2-A_Functions.h

#include <string>
#include <vector>

using namespace std;

#define FILE_IN  "Names10K.txt"

/* This function will be responsible for displaying the programs name,
   objective, and introduction. */
void Objective_screen();

/* This function will search for the file that contains the specified
   data from which the program depends upon. If the file is located
   the information is stored in the specifed array and program continues. 
   If not, the program will exit. */
bool ReadFile(string Names[], int &rTotal);

/* This function uses a modified version of the 'bubble sort' to sort
   the names from the data file. */
// void bubbleSort();
void Sort(string Names[], int rTotal);

/* This function will use references to obtain the user's input from the 
   function and then store the user's input for use later. */
void AskForName(string &rUserInput);

/* This function will use the stored user input for a search objective.
   The search objective will be compared with the contents of the data
   file for matching occurences. */
void SearchNames(string Names[], int rTotal, string UserInput, vector<string> &rvFirst,
				 vector<string> &rvLast);

/* This function takes the values that were obtained from the first few 
   parts of the program, and write them to a summary file. After the data
   is written to the specified file the program will output the results to
   the screen. */
bool WriteOutput(string Names[], int rTotal);

Functions

//   CLASS:		CIS 2275 C++ II
// PROGRAM:		Program #2-A (Revision)  |  C++ 10K NAME SEARCH
//  E-MAIL:		ppotter03@inbox.com
//    FILE:		P2-A_Functions.cpp

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

using namespace std;

// Specified data files
#define FILE_IN  "Names10K.txt"
#define FILE_OUT "Names10K_Results.txt"

void Objective_screen()
	{
	// Declared variables
	char ENTER;

	// Author, program title, and program objective.
	cout << "\n --------------------------------------------------------------   ";
	cout << "\n			C++ 10K NAME SEARCH							             ";
	cout << "\n --------------------------------------------------------------   ";
	cout << "\n			AUTHOR:		Page Lynn Potter							 ";
	cout << "\n			 CLASS:		CIS 2275									 ";
	cout << "\n	    ASSIGNMENT:		Program #2-A							     ";
	cout << "\n -------------------------------------------------------------- \n";
	
	cout << "\n This program will read 10,000 names (first and last) from a "
		 << "\n file, and store in an array. The names are counted and sorted "
		 << "\n (last, first). The user than enters in a name to search for, "
		 << "\n and the program searchs the names in the file. The search "
		 << "\n results are then reported to the user and also written to a "
		 << "\n program summary file. \n";
	cout << "\n TO BEGIN, PLEASE HIT THE ENTER KEY... \n";
	
	// Wait for user's input
	cin.get(ENTER);
}

bool ReadFile(string Names[], int &rTotal)
{	
	ifstream input;

	// c_str() to convert to char[] format
	input.open(FILE_IN); 

	if (! input)
		{
			return false;
		}

	rTotal = 0;
	
	// Counts the names in the file until it reaches the end.
	while (! input.eof())
	{
		FileInput >> Names[rTotal];
		++rTotal;
	}

	FileInput.close();

	return true;
}	
	
void Sort(string Names[], int rTotal)
{	
	// Test the unsorted array
	for (int i = 0; i < 10; ++i)
	{
		cout << "\n Unsorted First Ten Names: " << Names[i];
	} 

	string temporary;
	
	for(int A = 0; A < (rTotal - A); ++A)						
		{
		for(int B = 1; B < rTotal; ++B)							
			{
			if(Names[B - 1] > Names[B])
				{
					temporary = Names[B];							
					Names[B] = Names[B - 1];						
					Names[B - 1] = temporary;						
				}
			}
		}

	// Test the sorted array
	for (int i = 0; i < 10; ++i)
		{
			cout << "\n Sorted First Ten Names: " << Names[i];
		}
}
void AskForName(string &rUserInput)
{
	cout << "\n In CAPS, Enter In Name You'de Like To Search For:   ";
	getline(cin, rUserInput);
	cin.ignore();
	  
     // int index = rUserInput.find(" ");
 
      //rLast = rUserInput.substr(0,index-1);
      //rFirst = rUserInput.substr(index+1);
		
}

void SearchNames(string Names[], int rTotal, string rUserInput, vector<string> 
				 &rvFirst, vector<string> &rvLast)
{
	
	// Need to fix code below....

	for (int i = 0; i < rTotal; ++i)
		{
		int pos;
		pos = Names[i].find(rUserInput);
		
		int sppos;
		sppos = Names[i].find(" ");

			if( pos == -1)
				{
					continue;
				}
			else 
				{
					break;
				}

				if( pos < sppos)
					{
						rvFirst.push_back(Names[i]);
					}
			
				if( pos < sppos)
					{
						rvFirst.push_back(Names[i]);
					}
		}
}
			
bool WriteOutput(string Names[], int rTotal)
{
    string OutputFile = "Names10K_Results.txt";
	
	ofstream FileOutput;	

	FileOutput.open(OutputFile.c_str());								

	// Tests for output file
	if(!FileOutput)
	{
		cout << "\n		Opps! Error... Can't Locate The File \"" << OutputFile << "\"";
		cout << "\n ----------------------------------------------------- \n " << endl;
		
		return false;
	}
	else
	{
		cout << "\n Found Data Output File! \n";
		return true;
	}
	
		FileOutput << "\n --------------------------------------------------------------   ";
		FileOutput << "\n			C++ 10K NAME SEARCH							           ";
		FileOutput << "\n --------------------------------------------------------------   ";
		FileOutput << "\n			AUTHOR:		Page Lynn Potter						   ";
		FileOutput << "\n			 CLASS:		CIS 2275								   ";
		FileOutput << "\n	    ASSIGNMENT:		Program #2-A							   ";
		FileOutput << "\n -------------------------------------------------------------- \n";
		FileOutput << "\n -------------------------------------------------------------- \n";
		FileOutput << "\n		   RESULTS:												   ";  

		cout << "\n Check Output! ";
	
	
	FileOutput.close();
	
}
// END OF P2-A_Functions

Driver

//   CLASS:		CIS 2275 C++ II
// PROGRAM:		Program #2-A (Revision)  |  C++ 10K NAME SEARCH
//  E-MAIL:		ppotter03@inbox.com
//    FILE:		P2-A_Driver.cpp

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

using namespace std;

#include "P2-A_Functions.h"

int main()
{
		// Declared Variables
		string Names[10000], answer, rUserInput;
		string IN_FILE = "Names10K.txt", OUT_FILE = "Names10K_Results.txt";
		int rTotal = 0;
		vector<string> rvFirst;
		vector<string> rvLast;

		Objective_screen();

		do{
			
			bool OK = ReadFile(Names, rTotal);
			if(!OK)
				{
					cout << "\n ERROR! Can't Find The Input File: \"" << IN_FILE << "\"";
					cout << "\n .......Program Will Now Terminate....... \n";
					// If there is an error, this terminates program.
					exit(1);
				}
			else
				{
					cout << "\n SUCCESS! Found The Input File: \"" << IN_FILE << "\"";
					cout << "\n There's a Total Of " << rTotal << " Names In The File. \n" << endl;
				}
		
				
			Sort(Names, rTotal);

			AskForName(rUserInput);

			SearchNames(Names, rTotal, rUserInput, rvFirst, rvLast);
			
			SearchNames(Names, rTotal, rUserInput, rvFirst, rvLast);


			//if(result == true)
			//{
				//cout << "\n ERROR! Can't Find The Output File: \"" << OutputFile << "\"";
			//}
			//else
			//{
				//cout << "\n Opps! Error... Problem Writing To File. ";
				//exit(1);
			//}

			cout << "\n Search For More Name(s)? (YES / NO) ";
			getline(cin, answer);
			
		}while(answer == "YES");
		
	return(0);
}
// END OF C++ 10K NAME SEARCH

Edited 6 Years Ago by ppotter3: n/a

Comments
Very well directed questions and you are always polite!
Attachments
PEELER, MARY
BRANN, JENNIFER
PACK, CHRISTINE
WALLACE, VAN
BRODT, KATHERINE
JARRELL, ELOISE
BARRON, LEONILA
ATHERTON, STANLEY
CARDWELL, RUBY
JOYCE, SHARA
GARCIA, MARY
FRYMAN, WILLIAM
GONZALES, MARY
FARIA, TRISTAN
SKINNER, DEBORAH
MOORE, LUCILLE
MICHAEL, ELIZABETH
HEICHEL, JOHN
WEST, TIMOTHY
CRAWFORD, EDWARD
CONLEY, JOSHUA
PALMER, MITCHEL
MATHIS, KEN
MCGREGOR, DEBORAH
DENLEY, FLOYD
DOWNS, ALISSA
FULLER, YOLANDA
CHAPPEL, BARBARA
WASHINGTON, THOMAS
SILVA, LOUISE
BEAVERS, HEIDI
SCHUSTER, LUZ
CALL, MARGARET
BETTERS, DANIEL
SMITH, RYAN
LANDGRAF, LINDA
BRINKMAN, CLAYTON
SEDGWICK, BRUCE
MURPHY, ADELA
NUNN, CARL
TERRY, GLENN
FOWLER, JORGE
THOMPSON, GERALD
DAVIS, ANGEL
MCMILLIAN, LAURA
KINGSLEY, MAX
NORRIS, BEATRICE
ROBINSON, KATHLEEN
THOMAS, CANDACE
HAIRE, JOANN
ROSENBAUM, LISA
HOLSTINE, TRACI
BEAMON, GEORGE
JOHNSON, KAREN
GROYS, EARLINE
LANDRETH, GARY
DAVIS, HUGH
ROSE, ROBERT
PENA, EDWINA
EVANS, CYNTHIA
GILL, MARY
SPAHN, CHRIS
JOHNSON, TIMOTHY
GARCIA, LORI
GOMEZ, JOANN
COUCH, TEODORO
PARR, MICHELLE
RASMUSSEN, HARRY
ANDERSON, MATHEW
ROGERS, GLORIA
PORTER, KRISTEN
PERRY, KENNETH
KILLIAN, LEE
DORSEY, MICHAEL
WARD, NATHAN
CHAPMAN, ERNEST
BURKE, FELICE
WARREN, MICHAEL
OLDENKAMP, DELMA
RUBY, TIMOTHY
BATTSON, COLLIN
WEITZMAN, CLAYTON
TSHUDY, MARY
SCALES, MICHAEL
DOUGLAS, GARY
TRAINO, MARILYN
KILDAY, ISABEL
FLORES, KRISTA
HANSEN, DENNIS
SANDERSON, RUTH
AYERS, KAY
TAYLOR, WILLIAM
SCHMIDT, SARAH
PONTIOUS, FRANCISCO
FAULKNER, KIMBERLY
CARPENTER, SUZANNE
MILLER, VERNICE
SMITH, EVELYN
WHITTINGTON, MICHAEL
SANCHEZ, LISA
CHAVEZ, LACEY
JEFFERSON, JOSHUA
SCHRAM, DENNIS
PRENDERGAST, ERNEST
ABREU, MARY
AKBAR, DAVID
BUCO, ANNIE
BEASLEY, JOSEPH
LEVASSEUR, YVETTE
CAVALLO, JOANN
MCENTEE, RITA
MUNRO, MITZI
MONETTE, JAMES
HAVEN, AUGUSTA
COLLETTE, NANCY
BOURGET, CORA
SORENSEN, MARSHALL
AKIN, ARTURO
CLARK, CURTIS
WINKLER, JERRY
LAVOIE, BRANDON
CHESSMAN, DIXIE
COLLELO, DORTHA
WEEKS, LESLIE
TEGELER, JASON
FREEMAN, JOEL
BROWN, THADDEUS
BYASSEE, JOSEPH
LEWIS, JANET
JOHNSON, THERESA
HAIL, ELSIE
LONGSWORTH, EARNEST
LOWELL, CHAD
SMITH, MAUREEN
PEERY, BETH
PARTIS, JENNIFER
NICHOLS, DOLLIE
MONGELLI, SUSAN
BOWMAN, ROGER
BECK, SELENA
HUBBARD, RONALD
BRADFORD, HAROLD
WORDEN, JO
SALMERON, FRANKLIN
WILLIAMS, JOHN
MORRIS, MARGARITA
AUTEN, MARIA
REED, FREDERICK
ARMS, DONNA
ROWAN, LOUANN
CORDELL, YETTA
LEASURE, MYRTLE
HAGERMAN, TRACIE
BREEDEN, BEATRICE
INGRAM, FORREST
BUTLER, DERRICK
ELLIOTT, ANDREW
GREER, MARY
KAUR, ESTHER
WATKINS, ANITA
CLARK, BRIDGET
BRITT, JENNIFER
SALAZAR, RENEE
PLUMLEE, ROLAND
WINGO, BONNIE
WEBER, MARGARET
MITCHELL, TIMOTHY
COX, DOUGLAS
VANDESANDE, BONNIE
GORDON, DARIN
HESSE, MOISES
SCHWIPPS, TERRY
LEYENDECKER, SONYA
SONODA, JULIA
SMITH, ROD
BRANZ, TAMMY
LAFLAMME, KYM
MARSHALL, CHRISTOPHER
KAISER, JAMES
MORGAN, JORGE
SISSON, JAMES
VIRES, ANNE
DAVENPORT, MAX
RATLIFF, ADELA
DAVIGNON, FELICIA
DURST, PATRICIA
POKORNEY, JUAN
CASTRO, ALICE
PARKHURST, BENJAMIN
EASLEY, BONNIE
STURKIE, GRANT
ROGERS, FERNANDO
CHRISTIAN, DOROTHY
MCCRACKEN, CHARLES
PRUDEN, ANDREW
HAYMOND, KATHRYN
PEREZ, LOIS
ROSALES, ANN
CHATHAM, ELIZABETH
MORGAN, IVY
DELTON, CARRIE
MORABITO, CARLOS
WYLAM, JEFFREY
MCCORMICK, ZACHARY
TURNER, MARTHA
LEWIS, GLADYS
WEAVER, JO
KEISER, JOHN
COTE, JACQUELINE
FRANKLIN, PAMELA
TIGHE, ESTHER
MORIN, MARK
POEPPELMAN, THERESA
MATTHEW, BRYAN
HILL, CURTIS
FINNEGAN, JUSTIN
HARRISON, FLORENCE
TROUTT, DOUGLAS
LOPEZ, RICHARD
BLOOMQUIST, MATTHEW
JULIAN, RICHARD
SHECKLER, THOMAS
MILLER, VAUGHN
WAITMAN, APRIL
MOORE, LORENZO
KARPINSKI, BRANDON
MURPHY, JOHN
MCKINNEY, JAN
BRUNDAGE, MILDRED
RILEY, MARTHA
STEELE, ELMO
HARVEY, ANN
WILLIAMS, REGINALD
SMOTHERS, MARY
HALL, MARGARET
ESCOBAR, KIRSTEN
TURNER, FLORENCE
LITTLE, PATRICIA
BELMONT, GARY
LANE, ALICE
VALVERDE, IDELLA
VACHERESSE, GREGORY
MCLENDON, GARRY
SHUMATE, CATHERINE
DOMINGUEZ, MARTIN
CHILDERS, REBECCA
DWYER, JEANNIE
JOHNSON, TAMMY
SHAW, DAVID
STEEL, JOYCE
LUCEY, JAMES
CHONG, RYAN
BARNHART, PATRICIA
TAYLOR, JOHN
THOMPSON, RICKY
WALLER, BRIAN
DEBOSE, ANNIE
ITURBE, MITCHELL
HORNBECK, SIMON
FIELDS, RICHARD
RICKS, ROBERT
KIRBY, BRIAN
DONNELLY, HAROLD
MOON, WILLIAM
DERRICK, DALE
HEATH, WADE
NASWORTHY, RAMONA
CASEY, CHARLENE
JOHNSON, MARTHA
FRIEL, GENOVEVA
SIFFORD, KEITH
ROSS, MYRON
HYDE, GLENN
EVANS, GREGORY
ABRAMSON, CHRISTIE
VALENCIA, RYAN
CHAVEZ, ANGELA
DAVIS, MARIE
PERRY, JESSE
PICARD, CHERYL
LARSON, LOUIS
BELTRAN, HILDA
CHAPMAN, JENNIFER
SKEANS, MERYL
RUIZ, DOROTHY
CANGELOSI, CLEMENTINE
JEMISON, CHARLES
HILL, HASSAN
TOWNSEL, NORAH
WILSON, EDITH
SHIELDS, HOYT
HOWLIN, NATASHA
WESTMORELAND, CLARICE
GUTIERREZ, MARK
GUNDLACH, PATRICIA
WILLIAMS, ADRIENNE
MEYN, RONALD
DESMARAIS, TERRENCE
WALTERS, JUSTIN
LOPEZ, LULA
THOMPSON, WESLEY
HOLCOMB, STEPHEN
MCCLELLAN, IRMA
BANUELOS, ELLA
SUMMERS, JIM
WHITE, SHELIA
SMITH, DOUGLAS
NG, CHRISTOPHER
FARIA, ROBERT
NOLAND, CHRISTOPHER
CLANCY, GERALD
FREEMAN, JOSE
MANNING, BRIAN
LAFLEUR, BRIDGET
KELLEY, KRISTY
HADDEN, GERALDINE
GREY, MARSHA
LADNER, GEORGE
HATHAWAY, DENNIS
CANNATA, TAMMY
DIAZ, EDWARD
PATE, MICHAEL
LANE, GABRIEL
CARLTON, CLIFFORD
GREGORY, MICHAEL
NELSON, DONALD
MILIAN, MARY
JEWELS, ARMANDO
LANDRETH, TYRONE
BALDERAS, BRUCE
DICKMAN, CATHERINE
GUTIEREZ, ROSE
LAMPHERE, LARRY
KNIGHT, CHARLES
TRIAS, THERESA
HODGE, LAUREN
SHIPPY, ISRAEL
FOSTER, TED
EUNICE, JOHNNIE
MOUNTS, ESTHER
HALL, DEBRA
SOTO, PATRICIA
STONE, JAMES
BENEAR, LINDSEY
SMITH, RAUL
VANTASSEL, SAMUEL
PEREIDA, CARL
ALLEN, DONNELL
TICE, JASON
SANTIAGO, JOHN
MOORE, VERONICA
BRYANT, FREDERICK
MARROQUIN, CHRISTOPHER
STETLER, JAMES
STANCLIFF, RUBY
RAY, PATRICIA
GARCIA, MANUEL
LEUTHOLD, CATHI
HALLORAN, AVIS
DEMAIO, ROBERT
LAMB, CLARE
JARAMILLO, EMILY
EGGENBERG, RONALD
ALLRED, JASON
ISLAS, GUADALUPE
MILBURN, GEORGE
HANSING, CHRISTOPHER
CASILLAS, BLAKE
CONTI, JEROME
BISHOP, MARCELINO
COOPER, HOUSTON
TIFFANY, JAMES
RUMINSKI, AMY
JOHNSON, TAMEKA
PADILLA, FLORENCE
PETER, RODNEY
CASSIDY, BETTY
CRADER, BENNETT
SHRADER, ROSE
MCKINNEY, DANIEL
CARRASCO, MARY
FORD, SCOTT
YANCY, ELLA
WHITE, SANDRA
DYER, CHARLES
TOADVINE, CARL
SLOAN, LILLIAN
DUFFY, MARGARET
PENN, KEITH
SCHMITT, AMY
PETIX, WILLIAM
DONALDSON, JEFFREY
ANDERSON, LINDA
HIDES, MICAH
MCKINNEY, SYLVIA
TINSLEY, AMANDA
KIMBERLIN, CHRISTOPHER
SMITH, RICHARD
MICHAELS, LAVONNE
THOMPSON, MELISA
SKIDMORE, ALLEN
MCLAUGHLIN, JOSE
JONES, IOLA
BURKE, PATRICIA
ODOUGHERTY, LUIS
MARQUEZ, JOSEPHINE
FOSTER, GRACE
STEWARD, ALEXANDER
MELITO, STEPHANIE
WALKER, FLOSSIE
LOWRY, WALDO
GRADY, JASON
SHANE, MELVIN
PESSO, MICHAEL
MENDONCA, RENA
JONES, MICHAEL
HOLDER, ANDREW
HILL, LLOYD
ADAMS, COLUMBUS
DODSON, MARGARET
SAVAGE, ELIZABETH
PARK, ELEANOR
RUBIO, RONALD
HILTON, ISMAEL
TOLBERT, TONY
MELLON, PAMELA
SCHNEIDER, DONNA
BROWN, PAUL
NORTHROP, EDWIN
REILLY, ALEX
DOLAN, AMADA
LEWIS, LINDA
SLAYMAN, JARED
BOMAR, GEORGE
GARCIA, ROSARIO
CURTIS, ELAINE
WILLIAMS, CINDY
LYVERS, LINDA
YOCHUM, BILLY
SCHNEIDER, EMMA
NUGENT, KENYETTA
DAVIS, JAMES
GASPER, GREGORY
TONY, BRENT
BARBOSA, NEAL
KOCHANSKI, CAROL
HONEYCUTT, DANIEL
BAKER, KIMBERLY
CHANG, PATRICIA
BURGIN, SHARRON
PARENTI, JIMMY
PEOPLES, MARINA
DOVER, ALISA
CALVERY, TONI
TITUS, PATRICIA
JOHNSON, GWEN
ADAMS, IVA
HARRIS, DELORES
GARCIA, RICHARD
HOWARD, CHARLES
CRASS, DARYL
VANESS, THOMAS
LE, WILLIAM
VILLA, JAMES
NATHAN, DOROTHY
LEWIS, BRADLEY
PATTON, ROBERT
GREENFIELD, WILLIAM
ANDERSON, JAMES
RAGER, CANDANCE
BRADSHAW, KENNETH
DAILEY, ERVIN
SAHOTA, CONSTANCE
DEJESUS, MARY
BARNES, CONNIE
SHULL, VINCENT
CARLAN, REBECCA
MCCRACKEN, MARIA
MITCHELL, SARAH
KOMER, MARGARET
BURDICK, PAM
LANGFORD, DOMINIQUE
MUSSON, TARA
ROBINSON, MISTY
BALDWIN, LEWIS
STEWART, BOYD
REED, BETHANY
HILLMAN, JERRY
ALEXADER, ROBIN
PRESTON, ANGELA
JOHNSON, JENNIFER
BOYD, HARRY
CAMPBELL, ARTHUR
THOMPSON, KEVIN
SMITH, SHARON
SCHULER, BOBBY
HIGGINS, KATHLEEN
MCDONALD, BENJAMIN
SPENCER, GWENDOLYN
GREEN, SHARON
ANDREWS, JOEL
VAUTERS, DONNA
DETRICK, CATHERINE
VANDOREN, RON
FRAY, KAY
SOSA, ERIC
HERTENSTEIN, CHRISTOPHER
SCOTT, GERARD
COMPTON, KARA
HEICHEL, JAN
SALTER, CLAYTON
GOAD, TRAVIS
PARAMO, MARTHA
SHIPP, LORETTA
ROBSON, LEONARD
OLEARY, PRINCESS
SPRINKLE, JAMES
GARCIA, RAMON
HALL, JOSEPH
WARNER, LOIS
BARBEAU, THOMAS
HANEY, TIESHA
COMNICK, GENEVA
ACKERMAN, JONATHAN
BROOKS, JODY
BOOTH, CYNTHIA
PAZ, LANA
STEVENSON, BLANCA
STEVENS, ERMA
WALTERS, JANIE
HITE, CELIA
KNOPP, LAWRENCE
HESTERMAN, ERIC
TATE, MARY
PAIK, DAVID
PELLERIN, KATHERINE
BONNETT, KAREN
DOMINGUEZ, LATOYA
COMPTON, DOUGLAS
ISOM, SIDNEY
GRIFFIN, FELICIA
KILKENNY, JERRY
MOBERLY, EMILY
LANGLINAIS, JAMES
BEANBLOSSOM, CLEMENTINE
STEWART, CHI
MARKS, TAMMARA
KLEIN, SARAH
PEREZ, JOHN
DOYLE, BRIAN
CRAWFORD, MARY
CARRIAGA, WANDA
BOGGIONI, LOUIS
RAMOS, GRETCHEN
FLORES, VINCENT
HAMMOND, TAMEKA
CONRAD, ROBERT
REED, CHRISTINE
CUOMO, PATRICE
WRIGHT, VIVIAN
ROBERTSON, SANTOS
SANDFORD, PATRICIA
WEED, EDGAR
MCCLURE, NONA
COUTURE, PAMELA
STEIN, DAVID
LARSON, WAYNE
REED, ADRIANA
HUGLE, RAMON
BREAU, JUDITH
TIGNOR, WALTER
BERG, LYNDA
RICHARDS, BOBBY
XAYASITH, TONY
MARLOWE, MATTHEW
POTEET, REBECCA
AGUINIGA, MELLISA
LOCOCO, ANTONIO
NANCE, GEORGE
STENN, FREDERIC
BARNES, LYNN
FULTON, MARY
ROBERTSON, NICHOLE
BROTHERS, CHRISTINE
KEYS, ERMA
DEPERTE, APRIL
DRAKE, BROCK
CLARK, MARIA
STERNER, ROBERT
POPE, HAROLD
WERTZ, JAMES
STEAKLEY, DENISE
LARRIEU, ZACHARY
GOULD, JOHN
MILLER, ELISE
BELL, MARILYN
ZHOU, GAIL
MOSBY, IAN
BUZBEE, THOMAS
BROWNE, SUE
TERRY, KENNETH
REMPEL, SHEILA
GLENN, JAMES
VADASY, CHERYL
KLOECK, MARK
FRISCH, VIRGINIA
HASBERRY, WILSON
MOORE, JAN
BLY, WILLIAM
STARR, PAMELA
NEU, MARY
CALLEJA, JANET
MCCRACKEN, ANTONIO
HARDISON, ROBERTA
VIOLETTE, GEORGE
BROWN, JAMES
CARTER, EDGAR
JENSEN, ELMIRA
BOUDREAUX, MICHAEL
YOUNG, DANIEL
CRITCHFIELD, GREG
MARTINEK, MICHAEL
BELANGER, PAUL
YOUNG, CLARA
KEENER, DAVID
BOYD, ANDREW
DORAZIO, DIANA
ELUMBAUGH, JENNIFER
NEWTON, JAMES
HARRI

One good way to retrieve strings from a file is writing them to the file in a standard format.

What I do is add a special character like '@' or '$' before any input so that my file looks like this in the end :

@LastName@FirstName@Address@Telephone#\n

Then for retrieving the formatted text I'd use getline(fileToReadFrom, StringToSaveNewLine, SpecialCharacter) in a while loop.

This function saves a string from the file until it meets the special character you entered as a parameter in StringToSaveNewLine.
This way you'd know that LastName would always be in position 1, FirstName 2, and so on...

Like this.......

bool ReadFile(string Names[], int &rTotal)
{	
	ifstream input;

	// c_str() to convert to char[] format
	input.open(FILE_IN); 

	if (! input)
		{
			return false;
		}

	rTotal = 0;
	
	// Counts the names in the file until it reaches the end.
	while (! input.eof())
	{
		// Read names from file using ',' for delimiter?
		getline(input, Names[rTotal], ',');
		
		input >> Names[rTotal];

		input.ignore();

		++rTotal;
	}

	input.close();

	return true;
}

Thank you for that, one other thing.....
Now how would I search those and assign each to a vector? This hurts my brain.... But I want to learn how to be more efficient with strings and I/O.

Thank you for that, one other thing.....
Now how would I search those and assign each to a vector? This hurts my brain.... But I want to learn how to be more efficient with strings and I/O.

Once you isolate your whatever part of the string taken from the file you simply call your vector's function :

rvLast.push_back(myString);

push_back adds an element to the end of your vector :

Check this out :
http://www.cppreference.com/wiki/stl/vector/start

My driver and header file are the same, but how do I get the ReadFile() function to pick up the LAST, FIRST name instead of
FIRST, ?

//   CLASS:		CIS 2275 C++ II
// PROGRAM:		Program #2-A (Revision)  |  C++ 10K NAME SEARCH
//  E-MAIL:		ppotter03@inbox.com
//    FILE:		P2-A_Functions.cpp

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

using namespace std;

// Specified data files
#define FILE_IN  "Names10K.txt"
#define FILE_OUT "Names10K_Results.txt"

void Objective_screen()
	{
	// Declared variables
	char ENTER;

	// Author, program title, and program objective.
	cout << "\n --------------------------------------------------------------   ";
	cout << "\n			C++ 10K NAME SEARCH							             ";
	cout << "\n --------------------------------------------------------------   ";
	cout << "\n			AUTHOR:		Page Lynn Potter							 ";
	cout << "\n			 CLASS:		CIS 2275									 ";
	cout << "\n	    ASSIGNMENT:		Program #2-A							     ";
	cout << "\n -------------------------------------------------------------- \n";
	
	cout << "\n This program will read 10,000 names (first and last) from a "
		 << "\n file, and store in an array. The names are counted and sorted "
		 << "\n (last, first). The user than enters in a name to search for, "
		 << "\n and the program searchs the names in the file. The search "
		 << "\n results are then reported to the user and also written to a "
		 << "\n program summary file. \n";
	cout << "\n TO BEGIN, PLEASE HIT THE ENTER KEY... \n";
	
	// Wait for user's input
	cin.get(ENTER);
}

bool ReadFile(string Names[], int &rTotal)
{	
	ifstream input;

	// c_str() to convert to char[] format
	input.open(FILE_IN); 

	if (! input)
		{
			return false;
		}

	rTotal = 0;
	
	// Counts the names in the file until it reaches the end.
	while (! input.eof())
	{
		// Read names from file using ',' for delimiter?
		getline(input, Names[rTotal]);
		
		input >> Names[rTotal];

		input.ignore();

		++rTotal;
	}

	input.close();

	return true;
}	
	
void Sort(string Names[], int rTotal)
{	
	// Test the unsorted array
	for (int i = 0; i < 10; ++i)
	{
		cout << "\n Unsorted First Ten Names: " << Names[i];
	} 

	string temporary;
	
	for(int A = 0; A < (rTotal - A); ++A)						
		{
		for(int B = 1; B < rTotal; ++B)							
			{
			if(Names[B - 1] > Names[B])
				{
					temporary = Names[B];							
					Names[B] = Names[B - 1];						
					Names[B - 1] = temporary;						
				}
			}
		}

	// Test the sorted array
	for (int i = 0; i < 10; ++i)
		{
			cout << "\n Sorted First Ten Names: " << Names[i];
		}
}
void AskForName(string &rUserInput)
{
	cout << "\n In CAPS, Enter In Name You'de Like To Search For:   ";
	getline(cin, rUserInput);
	cin.ignore();
	  
	
     
	 // int index = rUserInput.find(" ");
 
      //rLast = rUserInput.substr(0,index-1);
      //rFirst = rUserInput.substr(index+1);
		
}

void SearchNames(string Names[], int rTotal, string rUserInput, vector<string> 
				 &rvFirst, vector<string> &rvLast)
{
	
	// Need to fix code below....

	for (int i = 0; i < rTotal; ++i)
		{
		int pos;
		pos = Names[i].find(rUserInput);
		
		int sppos;
		sppos = Names[i].find(" ");

			if( pos == -1)
				{
					continue;
				}
			else 
				{
					break;
				}

				if( pos < sppos)
					{
						rvFirst.push_back(Names[i]);
					}
			
				if( pos < sppos)
					{
						rvFirst.push_back(Names[i]);
					}
		}
}
			
bool WriteOutput(string Names[], int rTotal)
{
    string OutputFile = "Names10K_Results.txt";
	
	ofstream FileOutput;	

	FileOutput.open(OutputFile.c_str());								

	// Tests for output file
	if(!FileOutput)
	{
		cout << "\n		Opps! Error... Can't Locate The File \"" << OutputFile << "\"";
		cout << "\n ----------------------------------------------------- \n " << endl;
		
		return false;
	}
	else
	{
		cout << "\n Found Data Output File! \n";
		return true;
	}
	
		FileOutput << "\n --------------------------------------------------------------   ";
		FileOutput << "\n			C++ 10K NAME SEARCH							           ";
		FileOutput << "\n --------------------------------------------------------------   ";
		FileOutput << "\n			AUTHOR:		Page Lynn Potter						   ";
		FileOutput << "\n			 CLASS:		CIS 2275								   ";
		FileOutput << "\n	    ASSIGNMENT:		Program #2-A							   ";
		FileOutput << "\n -------------------------------------------------------------- \n";
		FileOutput << "\n -------------------------------------------------------------- \n";
		FileOutput << "\n		   RESULTS:												   ";  

		cout << "\n Check Output! ";
	
	
	FileOutput.close();
	
}
// END OF P2-A_Functions

Does this work for you?

//example

while (! input.eof())
	{
		// Read names from file using ',' for delimiter?
		getline(input, lastNameString, ',');
                myVector.push_back(lastNameString);
                int demiliterPosition = str.find(","); 
                firstNameString= fullString.substr (pos+1);
                myVector.push_back(firstNameString);
	}

Thank you, but what does this do? Could you explain (If its okay?), I want to learn why the code is used, so I can learn to implement that method or methods later.

Thank you, but what does this do? Could you explain (If its okay?), I want to learn why the code is used, so I can learn to implement that method or methods later.

Ofcourse,

Assuming you save a line from the text file with both the last and first name in a string called fullString...
Also you need to declare lastNameString and firstNameString...

if your entries in the file are in this format :

LASTNAME,FIRSTNAME\n
LASTNAME,FIRSTNAME\n

getline(input, lastNameString, ',');
// This line retrieves a string up to the point it meets the ',' character where it stops. It saves the string in the lastNameString without ofcourse the ',' character.

rvLast.push_back(lastNameString);
// lastNameString should now contain the last name of th person so you just add it to the last name Vector

int demiliterPosition = fullString.find(","); 
// the find() function returns the index of the string as an integer, so you save that to one of your variables to know where exactly ',' is.

firstNameString= fullString.substr (delimiterPosition+1);
// since fullString contains both names you know that what remains now is the first name which is right after the ','. The substr() function returns the substring of the string that calls the functions, from the index of the position given as a parameter until the end of the string. You don't want the ',' so you start from the next position. firstNameString should now contain the first name.

rvFirst.push_back(firstNameString);
//And you're done.

Sorry about the previous code, has some errors.
Anything else you'd like to know?

Thank you, I have another question....
Say in the ReadFile() function I want to read in 10000 names (LAST, FIRST) from that file..... How would I do that? Or would getline work?
Now can I read those names into a string Array[] ? If I can read them into that array, and then I sort them. Do I go on to the AskUserInput() function and get the users desired name to search for? Do I then split them using find()? Or do I search through the list and assign the results to the two different vectors when results are found? I am not sure logically how to do this, due to the fact that alot of this is pretty new to me...... Thank you once again for helping.....

Thank you, I have another question....
Say in the ReadFile() function I want to read in 10000 names (LAST, FIRST) from that file..... How would I do that? Or would getline work?
Now can I read those names into a string Array[] ? If I can read them into that array, and then I sort them. Do I go on to the AskUserInput() function and get the users desired name to search for? Do I then split them using find()? Or do I search through the list and assign the results to the two different vectors when results are found? I am not sure logically how to do this, due to the fact that alot of this is pretty new to me...... Thank you once again for helping.....

I'm not quite sure what you're asking but I'll give it a try.
If you save your last name and first name into two different vectors, the user would have no problem searching for a name by entering either a first or last name... you could then search the last name vector and find the occurences of the name given by the user in that vector. You could save the indexes of those occurences ( as in "Last name Smith was found in position 3, 8, 12 of the vector" ) and then print the corresponding indexes from the name vector.

Now one more thing... Do you want to use an array of Strings to save the names in? If so why? You could use two different arrays, one for last names and one for first names.

One tip :
Since you're working with a 10,000 name file, you could improve your search function.

If the user entered a name starting with W, X or Z your program would have to go through all 9500 names of irrelevant letters. That makes 9500 tries for 10000 strings
Look up the binary search algorithm :
for 2^N objects it takes up to N tries to find what you're looking for.
So for 2^15 names = 32768 names it would only take you 15 tries to find the desirable name.

http://en.wikipedia.org/wiki/Binary_search
It's fairly simple, but let me know if you have questions about that as well.

Edited 6 Years Ago by hermann87: n/a

The reason I wanted to store the names from the file in a array was, due to the fact that after filling the array (Send it to Sort())I would then sort it by last names, then first. After the array was sorted (data is then sent to the AskUserInput()) I would ask the user for their input and gather the input and send it to search(). In search I would look for the occurrences of Last names and send it to a vector, then look for the first names and send it to a vector. (This data is then sent to WriteOutput()) and the information is displayed.....
I hope this makes sense, its just kinda complicated, but It will help me become really strong with these data types and so fourth.

If this doesn't make sense let me know what parts, or where I am losing you.

I have tried to figure out binary search, but I just couldn't understand the examples on the web. I have looked for days straight to understand it. So I stuck with plain old linear search, but less efficient. I would use binary but I just cant seem to get it, I am a very visual learner so I like to be able to see why it does what exactly it does. Sometimes the web just throws syntax and I can;t put it into a example that is coherent to myself.

I have tried to figure out binary search, but I just couldn't understand the examples on the web. I have looked for days straight to understand it. So I stuck with plain old linear search, but less efficient. I would use binary but I just cant seem to get it, I am a very visual learner so I like to be able to see why it does what exactly it does. Sometimes the web just throws syntax and I can;t put it into a example that is coherent to myself.

The binary search algorithm is pretty easy :

Say you have an array of 1024 integers from 1 to 1024.
Now think of a number (int key) (or in your case "user searches for a name").
What's the quickest way to find it? This is what the binary search algorithm suggests :

We set the following integers :

int sortedArray[1024] = {1, 2, 3, 4, 5, ..., 1023, 1024};
int first = 0; // the first index of your array
int last = arraySize; //the last index


cin << key; // the number you're thinking that the algorithm will find
            // or the name the user entered in your program

while (first <= last) {                // you will see why this happens
       int mid = (first + last) / 2;  // compute mid point of the array each time.
       if (key > sortedArray[mid]) 
// the number you entered is larger than the middle point of the array
//that means we won't have to go through all the numbers lower than the mid point of the array so we kick em out of the search... this is how...
           first = mid + 1;         // we set the first index of our array to be the mid point we picked earlier... plus 1.

       else if (key < sortedArray[mid])  

// in case the number you entered was smaller
//instead of setting the first index higher, we set the last index lower... to mid - 1; just like we set the first to mid + 1; we don't want to include the value in mid another time so we go plus or minus 1

           last = mid - 1;       //we set the last index of our array to be the mid point we picked earlier... minus 1
       else // in case the number you entered was not larger or smaller
//that means we've found the number!
           return mid;           // found it... that is the number pointing the cell in which the value we're looking for is
   }
   return -(first + 1);        // failed to find key
}

To understand how the while loop works... try entering a number larger than 1024... or a negative number. You'll see what happens

Comments
Excellent post(s)

How to read the Last, First into a array? Thats where my problem seems to be. I can get the Last names in but not the first. How can I read them in?

while (! input.eof())
	{
		// Read names from file using ',' for delimiter?
		getline(input, Names[rTotal]);
		
		input >> Names[rTotal];

		input.ignore();

		++rTotal;
	}

This was overwriting the name you read in with the getline immediately after.

You want something like:

rTotal = 0;
while(getline(input,rTotal))  //uses default delimiter of '\n'
{
     rTotal++;   //can omit the braces if you want
}

which uses the state of the object returned from getline to drive the loop (nothing to read in -> 0, a null address, is returned, loop quits). This reads in your last, first into one string so now you can sort and search (btw, sorry if I gave you an aversion to the binary search in that other thread)

Now, everything works, except for I am still foggy on my search. here is what i have...

void SearchNames(string Names[], int rTotal, string rUserInput, vector<string> 
				 &rvFirst, vector<string> &rvLast)
{
	

// Need to fix code below....

// RIGHT, DO A FOR LOOP AND GO THROUGH THE WHOLE ARRAY ONCE.
// THE TRICK WILL BE TO LOAD THE FIRST AND THE LAST NAMES AT THE SAME TIME.
// SINCE THEY ARE ALREADY SORTED (IN NAMES ARRAY) IF YOU LOAD AS YOU GO, THEY'LL
// ALREADY BE SORTED.  MAKE SENSE TO YOU???



	for (int i = 0; i < rTotal; ++i)
		{
			int pos;
			pos = Names[i].find(rUserInput);

			int sppos;
			sppos = Names[i].find(" ");
			
			// If pos == -1 than continue, name isn't in the list.
			if( pos == -1)
				{
					continue; 
				}
		
			// If pos != -1 than the name is found.
			else  
				{
					
				}

			// If pos < sppos, then it's a last, push into vector.
			if( pos < sppos)
				{
					rvLast.push_back(Names[i]);	
				}
// NOW HERE'S THE TRICK. IF THE POS < SPACE, YOU NEED TO ALSO CHECK IF THE 
// USER'S NAME IS ALSO AFTER THE SPACE. THERE IS A FIND FUNCTION IN THE 
// STRING CLASS THAT LETS YOU PUT IN THE POSITION OF WHERE TO START LOOKING.

			int pos2 = Names[i].find(sppos, rUserInput);
			if( pos2 > sppos)
				{
					rvFirst.push_back(Names[i]);
				}
// SOMETHING (YOU'LL NEED TO DOUBLE CHECK) LIKE
// INT POS2 = NAMES[I].FIND(SPPOS, RUSERINPUT);    
// MIGHT BE THE OTHER WAY AROUND. THEN CHECK IF POS2 > SPACE POSITION, IT 
// ALSO IS A FIRST NAME, SO PUSH THE NAME INTO THE FIRST VECTOR.
					

// IF POS > SPACE, YOU KNOW IT'S A FIRST NAME, SO PUSH INTO FIRST
				if( pos > sppos)
					{
						rvFirst.push_back(Names[i]);
					}
		}
}

Based on the comments, and the edits I have made to the code, is this going to work? I basically want to find (LAST, FIRST) if I find a LAST I want to push it into a vector, but heres the trick if I find a LAST I still need to check after the ',' for the FIRST. I also need to make sure that if its not in the LAST I check the FIRST.
This is still kinda confusing to me.....
From what I have edited will this work?

void SearchNames(string Names[], int rTotal, string rUserInput, vector<string> 
				 &rvFirst, vector<string> &rvLast)
{
for (int i = 0; i < rTotal; ++i)
		{
			int pos;
			pos = Names[i].find(rUserInput);

			int sppos;
			sppos = Names[i].find(" ");
			
			// If pos == -1 than continue, name isn't in the list.
			if( pos == -1)
				{
					continue; 
				}
		
			// If pos != -1 than the name is found.
			else  
				{
					
				}

			// If pos < sppos, then it's a last, push into vector.
			if( pos < sppos)
				{
					rvLast.push_back(Names[i]);	
				}
int pos2 = Names[i].find(sppos, rUserInput);
			if( pos2 > sppos)
				{
					rvFirst.push_back(Names[i]);
				}
if( pos > sppos)
					{
						rvFirst.push_back(Names[i]);
					}
		}
}
This article has been dead for over six months. Start a new discussion instead.