In: Computer Science
Specification
The program should repeatedly prompt the user to enter a string of no more than 20 characters. The program will end when the user types in DONE (all caps). Use fgets to get input from the user.
Because fgets leaves the newline character on the string, the program should trim off the newline by replacing it with the null character, effectively shortening the string. Use strchr to locate the newline.
The program will use the input to build up a longer string. You may assume this string will be no longer than 1000 characters. The user input is compared to the longer string and then takes action as follows:
After each user input, display the longer string.
Sample Run
Here's a sample of how the program would work. I've shown user input in bold, just to help it stand out. Your program won't use any special typography.
Enter a string: hello hello Enter a string: world hello world Enter a string: bye bye hello world Enter a string: cat bye hello world cat Enter a string: worl bye hello world cat Enter a string: beep beep bye hello world cat Enter a string: bingo beep bye hello world cat bingo Enter a string: DONE beep byte hello world cat bingo
Let's analyze this one input at a time.
Please note that the program is not putting the words in alphabetic order. It's actually doing something simpler than sorting.
#include <stdio.h>
#include <string.h>
int main()
{
//Define a variable for input and output
string*/
char input[20];
char output[1000] = "";
// loop for getting input string
while(1)
{
printf("Enter a string:
");
// read input
string
if (fgets(input,
sizeof(input), stdin) == NULL)
{
printf("Fail to read the input string");
}
else
{
//find new line
char *ptr = strchr(input, '\n');
if (ptr)
{
//if new line found replace with null character
*ptr = '\0';
}
}
// if input is DONE
exit loop
if (strcmp(input,
"DONE") == 0)
break;
// If the input is
contained within the longer output, ignore it and restart
loop
if(strstr(output,
input)!=NULL )
{
printf("%s\n", output);
continue;
}
// if input is the
first sting entered, it is copied into the output string
else
if(strlen(output)==0)
strcpy(output, input);
// else if input is
greater than the output string , append the input onto the output
string with a space separating them.
else if(strcmp(output,
input)<0)
{
strcat(output, " ");
strcat(output, input);
}
// else if input is
less than the output string , prepend the input onto the output
string with a space separating them.
else if(strcmp(output,
input)>=0)
{
strcat(input, " ");
char temp[1000] = "";
strcpy(temp, input);
strcat(temp, output);
strcpy(output, temp);
}
printf("%s\n", output);
}
return 0;
}
Output