Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++

How to use puts() in C++

Sadia Zubair

The puts function is a C library function that writes a string to standard output. The function prints the passed string and appends the new line character at the end of the string. The function does not print the null character \0 or any character that comes after it in the string.

In order to use the puts function, the stdio header file needs to be included in the program:

#include <stdio.h>

Parameters

The function takes in one parameter: a string to be printed.

puts("Hello World")

Return value

Upon successful execution of the function, a non-negative integer value is returned. In case of any error, End-of-File (EOF) is returned.

#include <iostream>
#include<stdio.h>
using namespace std;

int main() {

    int val = puts("Hello World");
    cout << "The value returned from puts function is " << val << endl; 
     
    return 0;
    
}

Examples

  1. The code below shows the puts function writing the string to the standard output.
#include <iostream>
#include <stdio.h> 
using namespace std;

int main() {
 
  puts("Hello World");
  
  return 0;
  
}
  1. The code below shows that the puts function appends the newline at the end of each string; so, “Hello World” and “Hello User” are printed on separate lines.
#include <iostream>
#include <stdio.h> 
using namespace std;

int main() {

  puts("Hello World");
  puts("Hello User");

  return 0;
  
}
  1. The code below shows that the puts function stops reading the character when it encounters the null character. In line 8, the addition of the null character after “Hello” resulted in the remaining string not being printed to the standard output.
#include <iostream>
#include <stdio.h> 
using namespace std;

int main() {

  puts("Hello User");
  puts("Hello\0 User");
  
  return 0;

}

RELATED TAGS

c++

CONTRIBUTOR

Sadia Zubair
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring