C89 Programming Help! Write a program that sorts a series of words entered by th
ID: 664653 • Letter: C
Question
C89 Programming Help!
Write a program that sorts a series of words entered by the user:
Assume that each word is no more than 20 characters long. Stop reading when the user enters an empty word (i.e., presses enter without entering a word). Store each word in a dynamically allocated string using an array of pointers to keep track of the string, as in the remind2.c program in section 17.2 of your book. After all words have been read, sort the array (using any sorting technique) and then use a loop to print the words in sorted order.
***Use the read_line function to read each word as in remind2.c
Here's the read_line function:
int read line (char str, int n) int ch, i = 0; while ((ch = getchar()) != ' ')Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define WORD_LEN 50
#define WORD_LIMIT 20
int read_line(char str[], int n);
int int_cmp(const void* p, const void* q);
int main()
{
char n[WORD_LIMIT];
int i;
int *a;
a = malloc(n * sizeof(char));
for(i = 0; i < WORD_LEN; i++)
{
printf("Enter a word: ");
scanf("%c", &n[i]);
}
qsort(n, WORD_LEN, sizeof(char), int_cmp);
printf("In sorted order: ");
for(i = 0; i < n; i++)
printf("%c ", a[i]);
printf(" ");
return 0;
}
int int_cmp(const void* p, const void* q){
int n1 = *(int *) p;
int n2 = *(int *) q;
if (n1 < n2)
return -1;
if (n1 == n2)
return 0;
return 1;
}
int read_line(char str[], int n)
{
int ch, i = 0;
while ((ch = getchar()) != ' ') {
if (i < n)
str[i++] = ch;
}
str[i] = '';
return i;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.