English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Control Flow

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

C Language gets() and puts()

gets() and puts() are declared in the header file stdio.h. These functions are used for string input/Output operations.

C gets() function

The gets() function allows users to input some characters and then press the Enter key. All the characters entered by the user are stored in a character array. A null character is added to the array to make it a string. gets() allows users to input strings separated by spaces. It returns the string entered by the user.

Declaration

char[] gets(char[]);

Using gets() to read a string

#include <stdio.h>
void main(){
	char s[30];
	printf("Please enter a string? ");
	gets(s);
	printf("You entered %s", s);
}

Output result

Input string? 
www.oldtoolbag.com
You entered www.oldtoolbag.com

Using gets() function is risky because it does not perform any array binding checks and reads characters continuously until a new line (enter) is encountered. It is affected by buffer overflow, which can be avoided by using fgets(). fgets() ensures that the number of characters read does not exceed the maximum limit. See the following example.

#include <stdio.h>
void main() 
{ 
   char str[20]; 
   printf("Please enter a string? ");
   fgets(str, 20, stdin); 
   printf("%s", str); 
}

Output result

Input string? www.oldtoolbag.com Basic Tutorial Website
www.oldtoolbag.com Basic

C puts() function

The puts() function is very similar to the printf() function. The puts() function is used to print strings on the console, which are previously read using the get() or scanf() function. The function's purpose is: to return an integer value representing the number of characters printed on the console. Since it uses an extra newline character for string printing, moving the cursor to a new line on the console, the integer value returned by puts() is always equal to the number of characters appearing in the string plus1.

Declaration

int puts(char[])

Let's look at an example that uses gets() to read a string and puts() to print it on the console.

#include <stdio.h>  
#include <string.h>    
int main(){    
    char name[50];    
    printf("Please enter your name: ");    
    gets(name); //Read String from User    
    printf("Your name is: ");    
    puts(name);  //Display String    
    return 0;    
}

Output:

Enter your name: Seagull Li
Your name is: Seagull Li