Write a full program that reads in an arbitrary sequence of integers from the standard input, and writes them to the standard output in sorted order and with all duplicates removed. You may assume the input contains at most 100 integers.
#include <stdlib.h>
#include <iostream.h>
// a and b point to integers. cmp returns -1 if a is less than b,
// 0 if they are equal, and 1 if a is greater than b.
inlineint cmp (constvoid *a, constvoid *b)
{
int aa = *(int *)a;
int bb = *(int *)b;
return (aa < bb) ? -1 : (aa > bb) ? 1 : 0;
}
// Read a list of integers from stdin
// Sort (c library qsort)
// Print the list
int main (int argc, char *argv[])
{
constint size = 100; // array of 100 integers
int array [size];
int n = 0;
// read an integer into the n+1 th element of array
while (cin >> array[n++]);
n--; // it got incremented once too many times
qsort (array, n, sizeof(int), cmp);
for (int i = 0; i < n; i++)
cout << array[i] << "\n";
return 0;
}
This almost works, but I keep getting my numbers printed twice. Instead of printing, for example
This is actually really easy using std::set, but since I'm pretty sure the point of the exercise was to do the sorting and removing duplicates yourself, I won't get into that....
Couple of things to note:
The first three lines of your code really ought to be
1 2 3
#include <cstdlib> // stdlib.h is C, cstdlib is C++
#include <iostream> // iostream.h is non-standard
usingnamespace std;
You didn't check for duplicate values.
That's why your numbers are getting printed multiple times.
For instance, I ran this with this input:
1
2
3
3
3
3
4
33
2
and got this as output:
1
2
2
3
3
3
3
4
33
Which clearly shows you didn't remove the duplicate values. (Technically, you don't actually need to remove them from the array, you can probably just skip over them while printing the array)