I'm writing a small C programm that should sort comma separated strings alphabetically.
The input looks like this : "FSKT","EORD","OSEA","DA","ERTS","VG","FHR","EIAS","DOD"
This is the working code that does the sorting:
#include <stdio.h>
#include <string.h>
int main() {
char *a[] = {"FSKT","EORD","OSEA","DA","ERTS","VG","FHR","EIAS","DOD"};
const char *s1, *s2;
int compRes,i,j;
int length = 9;
for (i = 0; i < length; i++) {
for (j = i+1; j < length; j++){
s1 = a[i];
s2 = a[j];
compRes = 0;
while(*s1 && *s2){
if(*s1!=*s2){
compRes = *s1 - *s2;
break;
}
++s1;
++s2;
}
if (compRes > 0 || (compRes == 0 && *s1)) {
char* temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
printf("%s ", a[i]);
}
printf("\n");
return 0;
}
I'm not using strcmp() or something like that because it needs to stay very basic for later translation.
Now i would like to use scanf() for the input string and if a dot is reached the input should stop. Somehow I'm already stuck at the input...
This is my attempt so far, unfortunately it isn't working.:
#include <stdio.h>
#include <string.h>
int main() {
int compRes;
int i;
int j;
int length = 9;
char *s1;
char*s2;
char a[10][10] = { 0,0,0,0,0,0,0,0,0,0};
//scan all strings separated with a comma
scanf("%4[^,],%4[^,],%4[^,],%4[^,],%4[^,],%4[^,],%4[^,],%4[^,],%4[^,]" ,a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8]);
for (i = 0; i < length; i++) {
for (j = i+1; j < length; j++){
s1 = a[i];
s2 = a[j];
compRes = 0;
while(*s1 && *s2){
if(*s1!=*s2){
compRes = *s1 - *s2;
break;
}
++s1;
++s2;
}
if (compRes > 0 || (compRes == 0 && *s1)) {
char* temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
printf("%s ", a[i]);
}
printf("\n");
return 0;
}
Can someone help me?
Thanks in advance.