I've got an essay where is says "Given name and number of votes of two candidates, make two charts which one is sorted by the number of votes increasing, and the other in alphabetical order."
I've done the first part of the code already, and it's something like this:
#include <stdio.h>
int main () {
char candidato1[50], candidato2[50];
int voti1, voti2;
scanf("%s", &candidato1);
scanf("%s", &voti1);
printf("Ordine basato sul numero di voti in verso cresciente\n");
printf("%-10s %-10s\n", "Nome" "Numero di voti",);
if (voti1>voti2) {
printf("%-10s %-10d\n", candidato1, voti1);
printf("%-10s %-10d\n", candidato2, voti2);
}else {
printf("%-10s %-10d\n", candidato2, voti2);
printf("%-10s %-10d\n", candidato1, voti1);
}
printf("\n");
printf("Ordine alfabetico\n");
printf("%-10s %-10s\n", "Nome" "Numero di voti",);
//alphabetical order here
return 0;
}
As I've said in my previous post, I'm still new to c, and char are really a mystery for me. I've did some searches online but I couldn't find anything useful or clearly understandable for me. Hope someone here can help me figure it out.
CodePudding user response:
You could use strcmp
function from string.h
to compare strings in alphabetic manner. If it returns number > 0 than first string is greater then second, similarly, if it returns number < 0 than second string is greater then first, otherwise if it returns 0 than the strings are equal.
It would look like that:
if (strcmp(candidato1, candidato2) > 0) {
printf("%-10s %-10d\n", candidato1, voti1);
printf("%-10s %-10d\n", candidato2, voti2);
} else {
printf("%-10s %-10d\n", candidato2, voti2);
printf("%-10s %-10d\n", candidato1, voti1);
}
Do not forget to #include <string.h>