Printing ordered integers in arrays

Here are the specifications:

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.

And here's my code:

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
#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.

inline int cmp (const void *a, const void *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[])
{
  const int 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
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10


I get
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
10


Any thoughts would be amazing; I'm not seeing anywhere in this code from which my problem stems.

Thank you!
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
using namespace 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)
Topic archived. No new replies allowed.