String Input and Output Functions in C with Examples
In C, a string is a sequence of characters that is stored in an array. A string is typically represented by an array of characters, terminated by a null character slash 0 .
The syntax for declaring a string in C is as follows:
char string_name[size];
Where "string_name" is the name of the string variable and "size" is the maximum number of characters that the string can hold, including the null character.
For example:
char name[] = "AJAY";
This declares an array of characters called "name" and initializes it with the string "AJAY"
In C, there are several ways to input and output strings:
Using scanf() and printf() function
You can easily input and output a string using scanf() and printf() functions.
#include <stdio.h>
int main()
{
char str[100];
printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %s", str);
return 0;
}
This program uses the scanf() function to prompt the user to enter a string, which is then stored in the variable "str". The printf() function is then used to print the string.
Output:
Enter a string: Ajay Kumar
You Entered: Ajay
the scanf("%s", str) function reads only a single word, it stops reading when it encounters a whitespace, newline or tab.
Using gets() and puts() function
#include <stdio.h>
int main()
{
char str[100];
printf("Enter a string: ");
gets(str);
printf("You entered: ");
puts(str);
return 0;
}
This program uses the gets() function to prompt the user to enter a string, which is then stored in the variable "str". The puts() function is then used to print the string.
Output:
Enter a string: Ajay Kumar
You Entered: Ajay kumar
Using fgets() and fputs() function
#include <stdio.h>
int main()
{
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("You entered: ");
fputs(str, stdout);
return 0;
}
This program uses the fgets() function to prompt the user to enter a string, which is then stored in the variable "str". The fputs() function is then used to print the string.
It's important to note that the gets() function is now deprecated and should be avoided as it does not check the size of the input buffer and can cause buffer overflow. Instead, use the fgets() function which allows to specify the maximum number of characters to be read.
Also, the scanf("%s", str) function reads only a single word, it stops reading when it encounters a whitespace, newline or tab. To read a sentence or phrase with spaces, you should use gets() or fgets(str, sizeof(str), stdin);