As a note, problems like this are why you should never rewrite sorting yourself. There are libraries for that. It would be much cleaner to implement this using a map of char to int and just output the results based on highest count. However, the below should fix your immediate problem: