hi

my program is supposd to deleted repeated (identical) array elements within an array. Although its not working but I can figure out why?

Also is there a more advanced way of doing this; checking for repetitions in an array? I am not sure but maybe using stringstream?

I am reading in names from a text file & adding those names to an array, is there a way to read the file + store the names in array without repeats in one go. Instead of; reading the file & storing all names(repeats & all) in an array, then search the array for repeats & store in a new array?

heres my code

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

using namespace std;



int main()
{
	string names[7] = { "jim", "mag", "narelle", "jim", "helga", "mag", "kim" };
	string array[7];

	for (int i = 0; i < 7; i++)
	{
		for (int j = 0; j < 7; j++)
		{
			while ( names[i] != array[j] )
			{
				array[i] = names[i];
			}
		}
	}

//just for debugging.
	for (int i = 0; i < 7; i++)
	{
		cout << names[i] << " ";
	}

	cout << endl;

	for (int i = 0; i < 7; i++)
	{
		cout << array[i] << " ";
	}


	return 0;
}
Member Avatar for iamthwee

A more advanced way maybe to store the values in a vector.

Sort it then use unique on it.

Member Avatar for jencas

Use std::set! Just add all names to std::set and std::set will do the job for you.

you can't really delete an element from an array, about all you can do is blank it out.

int main()
{
	string names[7] = { "jim", "mag", "narelle", "jim", "helga", "mag", "kim" };
    int asize = sizeof(names)/sizeof(names[0]);

	for (int i = 0; i < asize; i++)
	{
        if( names[i] == "")
            continue;
		for (int j = i+1; j < asize; j++)
		{
			if( names[i] == names[j] && names[j] != "")
			{
				names[j] = "";
			}
		}
	}
    for(int i = 0; i < asize; i++)
    {
        if( names[i] != "")
            cout << names[i] << "\n";
    }
	return 0;
}

>>is there a way to read the file + store the names in array without repeats in one go.

Yes. One approach might be to:

1) Declare the final array with enough elements to hold all the data you want. Vectors work better because they are self expanding so you don't have to specify the maximum number of elements that can be added.
2) Declare an int to keep track of how many elements you have actually placed in the array and initialize it to zero, lets call it count.
3) Obtain the value you wish to insert into the array. How you get the value is up to you
4) Loop through the array elements already added to the array to see if you find the value you want to add.
5) If you find it, break out of the loop and move on to the next value to insert, if any.
6) If you don't find it add it to the array wherever you feel most appropriate and icrement count.

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.