193k views
4 votes
In this lab you will write a C program to sort an array of strings. The program will: Create an array of 50 strings; each string can hold up to 30 characters. Write a function to read strings from the file "strings.dat" into your array. Read until EOF and keep track of how many strings you read, as it may be less than 50. Then pass this variable to your print and sort functions so they know how many strings to print and sort. Use fopen to open the file and fgets to read each string. Write a function to sort the strings. Only sort the array entries that contain strings read from the file. See below for pseudocode for selection sort. Write a function to swap two strings, which will be called by your sort function. Pass the array and the subscripts of the two strings that need to be swapped. Write a function to print out the array entries that were read into the array. Use printf. Your main function should call the functions to read into the array, print the array, sort the array, and print the array again.

User Artal
by
4.0k points

1 Answer

4 votes

Answer:

See explaination

Step-by-step explanation:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

void swap(char *arr[], int i, int minIdx)

{

char temp[30];

strcpy(temp, arr[i]);

strcpy(arr[i], arr[minIdx]);

strcpy(arr[minIdx], temp);

}

void sort(char *arr[], int n)

{

for (int i = 0; i < n - 1; i++)

{

int minIdx = i;

int minV = 10000;

char min[30];

strcpy(min, arr[i]);

for (int j = i + 1; j < n; j++)

{

int a = strcmp(min, arr[j]);

if (a < 0)

{

strcpy(min, arr[i]);

minIdx = j;

}

}

swap(arr, i, minIdx);

}

}

void print(char *arr[], int n)

{

for (int i = 0; i < n; i++)

printf("%s", arr[i]);

}

void read(char *arr[], int *n)

{

FILE *file = fopen("strings.dat", "r");

char line[30];

*n = 0;

printf("Reading from file...\\");

while (fgets(line, 30, file))

{

strcpy(arr[(*n)++], line);

}

print(arr, *n);

}

int main(int argc, char const *argv[])

{

char *arr[50];

for (int i = 0; i < 50; i++)

arr[i] = (char *)malloc(sizeof(char) * 30);

int len;

int n = 0;

read(arr, &n);

printf("\\-------------------------\\After sorting\\");

sort(arr, n);

print(arr, n);

}

User Sid Malani
by
4.3k points