Wrong program output (in some cases)

My program in some cases outputs extra spaces and endlines.

I have been looking at the code and I am unable to detect what is wrong. I am almost sure it is a stupid mistake I made but I am not able to see it.

For those who wonder, this program reads a sequence of lists of numbers, each one composed of a natural n followed by n integer numbers, and prints each list sorted in decreasing order.

My program must print each line sorted in decreasing order, with the numbers separated by a space.

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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool sorting_way (int i, int j) { 
	return i > j; 
}

int main () {
	int size;
	while (cin >> size) {
		vector <int> data (size);
		for (int i = 0; i < size; ++i) {
			int numbers;
			cin >> numbers;
			data[i] = numbers;
		}
		sort (data.begin(), data.end(), sorting_way);
		for (int j = 0; j < size; ++j) {
			if (j+1 == size) cout << data[j] << endl;
			else cout << data[j] << " ";
		}
	}
}


Example:

Input
8 1 -2 3 -4 5 -6 7 -8
4 0 1 1 0

Output
7 5 3 1 -2 -4 -6 -8
1 1 0 0
Last edited on
Could you give an example? What output do you get and how does it differ from what you want?
I cannot see how does my output look like when my program is wrong because it is part of a "private sample". The only outputs I know are the "public samples" and the example I added in the main post is one of it. What I can say is the following:
Your program seems 'almost correct'. That is, your program did not crash with any test case, it was fast enough compared to the Jutge's solution, and its output for every case always (nearly) matched the output of the Jutge's solution. Except for some small mismatches, your program would get an AC. Check for additional or missing empty lines, additional or missing spaces, tabs (none of our problem's output has tabs), and distractions related to lowercase and uppercase letters.
Last edited on
Maybe the problem is that you do not output an empty line when the size is zero.
Seems it was, what you just suggested. Now, program gives ALWAYS correct output.

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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool sorting_way (int i, int j) { 
	return i > j; 
}

int main () {
	int size;
	while (cin >> size) {
		if (size == 0) cout << endl;
		else {
			vector <int> data (size);
			for (int i = 0; i < size; ++i) {
				int numbers;
				cin >> numbers;
				data[i] = numbers;
			}
			sort (data.begin(), data.end(), sorting_way);
			for (int j = 0; j < size; ++j) {
				if (j+1 == size) cout << data[j] << endl;
				else cout << data[j] << " ";
			}
		}
	}
}


Thanks
Last edited on
Topic archived. No new replies allowed.