Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Searching an array for a string - help please

    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.

    Code:
    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

  • #2
    Supreme Overlord Spookster's Avatar
    Join Date
    May 2002
    Location
    Marion, IA USA
    Posts
    6,280
    Thanks
    4
    Thanked 83 Times in 82 Posts
    If we give you the code do we get credit for the homework assignment?
    Spookster
    CodingForums Supreme Overlord
    All Hail Spookster

  • #3
    Senior Coder tomws's Avatar
    Join Date
    Nov 2007
    Location
    Arkansas
    Posts
    2,644
    Thanks
    29
    Thanked 330 Times in 326 Posts
    Quote Originally Posted by Advancedkill View Post
    I don't suppose anyone could offer up some code to do this?
    Yes: strcmp().

    See also: freeloader.
    Are you a Help Vampire?


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •