1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
|
// ********************************************************************
// This program implements a function to return a dynamic array
// that deletes repeated characters.
// ********************************************************************
#include <iostream>
#include <limits.h>
using namespace std;
char *delete_repeats(char letters[], int size, int& numLetters);
bool isInArray(char arr[], int size, char target);
void runAgain(bool& run);
// ====================
// main function
// ====================
int main()
{
bool run;
do
{
char a[140];
char *noRepeats = NULL;
int size = 0;
int numLetters;
cout << "ENTER A STRING OF CHARACTERS \n";
cout << "(up to 140 characters)\n";
a[size] = cin.get();
while ((size < 140) && (a[size] != '\n'))
{
size++;
a[size] = cin.get();
}
numLetters = size;
cout << "\nYOU ENTERED " << size << " CHARACTERS \n";
for (int i=0; i<size; i++) cout << a[i] ;
cout << endl;
cout << "\nDELETING REPEATS\n";
noRepeats = delete_repeats(a, size, numLetters);
for (int i=0; i<numLetters; i++)
{
cout << *(noRepeats + i);
}
cout << endl;
delete [] noRepeats;
runAgain(run);
}while(run);
return 0;
}
// This function returns true if the given char
// is in the char array, and false otherwise
bool isInArray(char arr[], int size, char target)
{
for(int i = 0; i < size; i++)
{
if (arr[i] == target)
return true;
}
return false;
}
// This function scans through the input letters
// and copies them into a temporary buffer.
// The temporary buffer is then copied into a
// dynamic array that exactly holds the data.
char* delete_repeats(char letters[], int size, int& numLetters)
{
char *temp = NULL; // Holds unique chars
char *trimmed = NULL; // Unique chars with no empty space
numLetters = 0;
temp = new char[size];
for(int i = 0; i < size; i++)
{
if (isInArray(temp, size, letters[i]) == false)
{
*(temp + numLetters) = letters[i];
numLetters++;
}
}
trimmed = new char[numLetters];
for(int k = 0; k < numLetters; k++)
{
*(trimmed + k) = *(temp + k);
}
delete [] temp;
// Return new array
return trimmed;
}
void runAgain(bool& run)
{
char ans;
cout<<"Would you like to run again?(y/yes any other char/no):";
cin>> ans;
if (ans == 'Y' || ans == 'y') run = true;
else run = false;
}
|