I got a word count assignment and the requirements are shown below:
INPUT
The input contains words in several lines and in each line there could be more than one word. The input only contains English words, separated by space or line breaks. Words are case-sensitive.
OUTPUT
Print the words in alphabetic order with the corresponding appearance count in the text. For each word, please print the result in a single line (separate the word and the number with space).
Sample Input:
Computer system
computer design
algorithm design and analysis
quantum computer
computer science Department
Sample Output:
Computer 1
algorithm 1
analysis 1
and 1
computer 3
department 1
design 2
quantum 1
science 1
system 1
I tried something shown below and actually got the same output as the sample but still got marked as wrong answer by the assignment judge system.
Is there anything I did wrong?
#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
#include <iterator>
#include <vector>
using namespace std;
int main() {
string whole;
string line;
string word;
do {
getline(cin, line);
whole += line + ' ';
} while (!line.empty());
if (!whole.empty()) {
istringstream iss(whole);
vector<string> results((istream_iterator<string>(iss)), istream_iterator<string>());
int count = 1;
int size = results.size();
if (size == 1) cout << results[0] << ' ' << count;
else {
sort(results.begin(), results.end());
for (int j = 0; j < size; j++) {
if (j != size - 1) {
if (results[j] != results[j + 1]) {
string word = results[j];
cout << word << ' ' << count << endl;
count = 1;
}
else if (results[j] == results[j + 1]) count++;
}
else if (j == size - 1) {
if (results[j] != results[j - 1]) {
string word = results[j];
cout << word << ' ' << count << endl;
}
else if (results[j] == results[j - 1]) cout << results[j] << ' ' << count << endl;
}
}
}
}
return 0;
}