In this tutorial, you will learn about the two functions that are used in String, gets() and puts() function in C. Learn more on String.
How o read and write a line of text in C
gets() and puts() function are used for reading and writing a line of text or String in C. These both functions are included in a header file stdio.h
.
gets() function in C
This gets() when used in a program allowed the user to enter the characters or line of text until the user encountered the new line or you can say until the user presses the enter key. It also allows the space-separated line of text or String.
It is used in the program in the following manner:
C Program for gets() function.
1 2 3 4 5 6 7 8 9 10 11 | #include<stdio.h> int main () { char str[40]; printf("Enter the text: "); gets(str); printf("You have entered: %s", str); return 0; } |
Output:
1 2 | Enter the text: This is simple2code.com. You have entered: This is simple2code.com. |
Although, gets()
function is risky to use, the program might throw a warning when you used gets() because it does not check the array bound and keep on taking character until the new line is entered. This can be avoided by the use of fgets() function which only reads the character to the limit stated in the program.
C Program for fgets()
function.
fgets() function takes three argument:
- Name of the String,
- The size that is the number of character to read,
- stdin which is the standard input to take input from the keyboard.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <stdio.h> int main() { char str[20]; printf("Enter the text: "); fgets(str, 20, stdin); //display printf("You have entered: %s",str); return 0; } |
Output:
1 2 | Enter the text: This is simple2code. You have entered: This is simple2code. |
puts() function in C
puts() function works in a manner similar to printf() function. It is used to print or display the string in C and moves the cursor to the first position.
C Program for puts()
function.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include<stdio.h> int main() { char name[30]; printf("Enter the text: "); gets(name); //reads printf("You have entered: "); puts(name); //displays return 0; } |
Output:
1 2 | Enter the text: This is simple2code. You have entered: This is simple2code. |
C Program for fputs()
function.
fputs() takes two argument:
- Name of the String itself,
- stdout which is the standard output to display on the screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <stdio.h> int main() { char str[30]; printf("Enter the Website: "); gets(str); //reads printf("You have entered: "); fputs(str, stdout); //prints return 0; } |
Output:
1 2 | Enter the Website: This is simple2code. You have entered: This is simple2code. |