In: Computer Science
Please explain step by step what is going on each step
Also show how the output is coming. I would rate positively.
Thank you so much .
#include
<stdio.h>
#include <string.h>
int main()
{
char
buffer[16], *pos;
printf("Enter
string: ");
if
(!(fgets(buffer,sizeof(buffer),stdin)))
{
printf("End
of file\n");
return
0;
}
printf("Length
of %s is %lu
\n",buffer,strlen(buffer));
if
((pos=strchr(buffer, '\n')) !=
NULL)
*pos
= '\0';
printf("Length
of %s is now
%lu \n",buffer,strlen(buffer));
return(0);
}
Explanation:
#include <stdio.h>
#include <string.h>
int main()
{
// Below declaring a string (character array of size 16 characters)
and one pointer variable
char buffer[16], *pos;
printf("Enter string: ");
// check whether we are giving a string or EOF((ctrl + d) for end
of file in terminal) character.
if (!(fgets(buffer,sizeof(buffer),stdin))) {
// if we tap (ctrl + d) the above condition
satisfies, we print ""End of file" and we end the execution.
printf("End of file\n");
return 0;
}
// in buffer[16] we can store 15 characters and extra one space
is for storing null character('\0')
// printing the entered string and length of buffer
printf("Length of %s is %lu
\n",buffer,strlen(buffer));
// If enter string contain \n we are removing the '\n' at the end
of the input line
// strchr returns pointer to the first occurrence of the character
given(\n) and we are replace it with end of character(\0)
if ((pos=strchr(buffer, '\n')) != NULL)
*pos = '\0';
// printing the entered string and actual length of string after
removing \n
printf("Length of %s is now %lu
\n",buffer,strlen(buffer));
return(0);
}
Input & Output:
case 1:
Enter string: Hai Welcome
Length of Hai Welcome
is 12
Length of Hai Welcome is now 11
case 2:
Enter (ctrl + d) after run it shows below output.
Enter string: End of file
case 3:
Enter string: abcdefghijklmnopqrstuvwxyz
Length of abcdefghijklmno is 15
Length of abcdefghijklmno is now 15
In case 3 we don't have '\n' , so the length is same in two cases.