Write an ANSI-C program that reads user input strings line by line, until a line
ID: 3853761 • Letter: W
Question
Write an ANSI-C program that reads user input strings line by line, until a line of xxx is entered. The program then outputs the inputs after reordering the first 6 rows of inputs.
Assume that there are no more than 30 lines of inputs, and also assume that there are at least 6 lines of inputs. Assume that each line contains no more than 50 characters. Note: each line of input may contain spaces. • use fgets(.., 50, stdin) to read in a line. Note that a trailing is also read in. • use a 2D array to store the user inputs. That is, similar to lab4, define something like records[30][50] • when all the inputs have been read in (indicated by “xxx”), exchange row 0 and row 1 in main(), and then send the array to a function exchange() to exchange some other rows. • define a function void exchange(char[][50])which takes as argument an 2D array, and swaps the record in row 2 with that in row 3, and swaps row 4 with the row 5. Assuming the array has at least 6 rows. • define a function void printArray(char[][50], int n)which takes as argument an 2D array, and then prints the first n rows of the records on stdout. Use this function in main to display all the rows of the array
Sample OUTPUT:
indigo 329 % a.out Enter string: this is input 0, orange is orange Enter string: this is input 1, apple is greern Enter string: this is input 2, cherry is red Enter string: this is input 3, banana is yellow Enter string: this is input 4, do you like them? Enter string: this is input 5, yes bye Enter string: this is input 6, bye Enter string: xxxExplanation / Answer
#include <stdio.h>
#include<string.h>
int compare_strings(char a[], char b[]);
void swap(char *str1, char *str2);
void exchange(char [][50]);
void printArray(char [][50]);
int main(void)
{
char records[30][50], name[30];
int flag;
for(int i=0;i<30;i++){
printf("Enter string: ");
fgets (records[i], 50, stdin);
flag = compare_strings(records[i], "xxx ");
printf("%d ",flag);
if(flag == 0){
if (i < 6){
printf("Minimum 6 lines are needed to complete. ");
}else{
break;
}
}
}
return 0;
}
int compare_strings(char a[], char b[]){
int c = 0;
while (a[c] == b[c]) {
if (a[c] == '' || b[c] == '')
break;
c++;
}
if (a[c] == '' && b[c] == '')
return 0;
else
return -1;
}
void swap(char *str1, char *str2){
char *temp = (char *)malloc((strlen(str1) + 1) * sizeof(char));
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
}
void exchange(char arr[][50]){
char temp[50];
for (int i=0;i<30;i=i+2){
swap(arr[i],arr[i+1]);
}
return;
}
void printArray(char arr[][50]){
for(int i=0;i<30;i++){
printf("%s ",arr[i]);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.