...

View Full Version : Searching an array for a string - help please



Advancedkill
07-27-2009, 10:01 AM
Hi

I have a program that reads in names form a text file, with the number of names at th ebeginning of the file e.g.

3
Tom
Dick
Harry

then stores them in an array.


main ()
{
FILE *fin = fopen ("test.in", "r"); //File i'm reading in from
FILE *fout = fopen ("test.out", "w");

int N = 0; //The number of names in the file
fscanf(fin, "%d", &N);

char people[10][15]; //My array to store the names of the people, where I can store up to 10 people who have names up to 14 characters long (but is [15] not [14] so I can store the null character at the end of each name)

int i = 0;
for(i=0;i<N;i++)
{
fscanf(fin, "%s", &people[i]); //Stores everyone's name
}

exit (0);
}

Now what I want to do after I have read in and stored the names is, further down in my input text file, have one of the names repeated and then get a function to tell me at which point in the array that name is stored. e.g.

3
Tom
Dick
Harry
Dick

Would have my new function return 1 as in my "people" array Tom is at people[0], Dick is at people[1] and Harry is at people[2]. I want this new function (which will probably end up being a couple of lines long) to return an int value to my main function (shown above) where the int returned is the answer I'm looking for, so the inputs to this new function will have to be a)my "people" array and b)another char array but this time storing a single name

I don't suppose anyone could offer up some code to do this?
Thanks

Spookster
07-27-2009, 10:08 AM
If we give you the code do we get credit for the homework assignment?

tomws
07-27-2009, 01:56 PM
I don't suppose anyone could offer up some code to do this?


Yes: strcmp() (http://cplusplus.com/reference/clibrary/cstring/strcmp/).

See also: freeloader (http://wordnetweb.princeton.edu/perl/webwn?s=freeloader).



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum