I'm currently trying to attempt to alphabetize a list. I'm trying to have the user input a line containing the number of words to sort. Each following line will be entering a new word. The words will not contain spaces and will end with a line return. I know the easy way would be to read everything in using scanf
or fgets
, however my microprocessor cannot handle those functions forcing me to use getchar()
. As of now, when it prints out the sorted list, it just prints garbage. I feel like something is wrong with my code, but I am very new to programming and cannot figure it out. Any help is appreciated.
#include <stdio.h>
#include <string.h>
int main()
{
int i, j;
char string[10][20], temp[20];
int num;
while(1)
{
char ch = getchar();
if(ch == 0)
continue;
if(ch <= 0x39 && ch >= 0x30)
{
putchar(ch);
num = ch - 0x30;
}
if(ch == 0x0D)
printf("\n\r");
if (ch <= 0x7A && ch >= 0x61)
{
putchar(ch);
for(i=0; i<=num; i++)
{
for(j=0; j<=20; j++)
string[i][j] = ch;
}
}
if(ch== 0x20)
break;
}
for (i = 0; i < num - 1 ; i++)
{
for (j = i + 1; j < num; j++)
{
if (strcmp(string[i], string[j]) > 0)
{
strcpy(temp, string[i]);
strcpy(string[i], string[j]);
strcpy(string[j], temp);
}
}
}
printf("\nSorted Names\n");
for (i = 0; i < num; i++)
{
printf("%s\n", string[i]);
}
return 0;
}
First, you need to NULL-terminate the strings you read in. So you should change your check for a return to:
if ( ch == 0x0D )
{
string[i][j] = '\0';
printf( "\n\r" );
}
Second, you are reading a character at a time, but then you do a for loop for each character. This is completely wrong. You need to track i and j within the while loop and put each character into the correct spot as you go. I'm not going to write this out for you as it's pretty simple: Get rid of the double for loops when a character between 'a' and 'z' is received and just set string[i][j] = ch and then increment j. Just check to make sure j is less than 20 first.
Then, you just increment i every time you see a 0x0D character, and change your while loop to exit when i >= num.
Also, I would put your read of num in a separate loop before the one reading the words so that you can check for the user entering data in the proper order. You don't want to start reading words until the user has entered a number so you know how many to read.