In: Computer Science
Write a C program that repeatedly prompts the user for input at a simple prompt (see the sample output below for details). Your program should parse the input and provide output that describes the input specified. To best explain, here's some sample output:
ibrahim@ibrahim-latech:~$ ./prog1
$ ls -a -l -h
Line read: ls -a -l -h
Token(s):
ls
-a
-l
-h
4 token(s) read
$ ls -alh
Line read: ls -alh
Token(s):
ls
-a
-l
-h
2 token(s) read
$ clear
Line read: clear
Token(s):
clear
1 token(s) read
$ exit ibrahim@ibrahim-latech:~$
Note that the first and last lines are not part of program output (i.e., they are of the terminal session launching the program and after its exit). The program prompts the user (with a simple prompt containing just a $ followed by a space) and accepts user input until the command exit is provided, at which point it exits the program and returns to the terminal. For all other user input, it first outputs the string Line read: followed by the user input provided (on the same line). On the next line, it outputs the string Token(s):. This is followed by a list of the tokens in the input provided, each placed on a separate line and indented by a single space. For our purposes, a token is any string in the user input that is delimited by a space (i.e., basically a word). The string n token(s) read is then outputted on the next line (of course, n is replaced with the actual number of tokens read). Finally, a blank line is outputted before prompting for user input again. The process repeats until the command exit is provided. Hints: (1) An array of 256 characters for the user input should suffice (2) To get user input, fgets is your friend (3) To compare user input, strcmp is your friend (4) To tokenize user input, strtok is your friend Turn in your .c source file only that is compilable as follows (filename doesn't matter): gcc -o prog1 prog1.c Make sure to comment your source code appropriately, and to include a header providing your name.
Complete code in C:-
#include <stdio.h>
#include <string.h>
// Main function
int main(void) {
// 'token' variable keeps count of tokens
int tokens;
// 'string[]' array will take user input.
char string[256];
// Taking user input.
fgets(string, 256, stdin);
// Printing output.
printf("$ ");
// This while loop will run until "exit" entered as
input by user.
while(strcmp(string, "exit\n") != 0) {
// Printing output.
printf("Line read: %sToken(s):",
string);
// Fetching first token from input
string.
char *token = strtok(string, "
");
// Initializing 'tokens' as
0.
tokens = 0;
// Fetching all tokens from input
string.
while(token != NULL) {
printf("\n%s",
token);
token =
strtok(NULL, " ");
tokens++;
}
// Printing output.
printf("%d token(s) read\n",
tokens);
printf("$ ");
// Again taking user input.
fgets(string, 256, stdin);
}
return 0;
}
Screenshot of output:-