puts in C/C++: display string

Hey there! Today, we’re diving into the puts function. It’s a staple in C for writing strings to standard output (usually, this means displaying it on the screen). We’ll start by examining how to utilize this function, move on to some examples, and wrap up with hands-on exercises for you to try out.

Illustration of puts
Похожее
vector::push_back in C++: Adding Elements to a Vector
C++ offers various ways to manipulate data. The push_back function is a popular way to add elements to a vector. In this article, we'll delve deep into this function, exploring how and when to use it, and discuss some intriguing aspects related to it.
go

How to display a string on the screen in C/C++

To print a string to the screen, you can employ the puts function. You can use this function after you include the header file <stdio.h>. If you’re working in C++, include <cstdio>. Here’s how the function looks like:

int puts ( const char * str );
  • The sole argument it accepts is a pointer to the string you want to display.
  • In case of an error, the function will return -1. Otherwise, puts will return a positive number (which could be any number).

Let’s take a look at an example:

#include <stdio.h>

int main() {
  int n = puts("C puts");
  printf("n = %d \n", n);

  return 0;
}

The program’s output:

C puts
10 

One key thing to note: puts appends a newline character '\n' at the end of its output. This means you don’t have to add it yourself:

puts("AB");
puts("CD");

This will display:

AB
CD

In this aspect, puts differs from printf, which doesn’t automatically add a newline:

printf("AB");
printf("CD");

The output for this will be:

ABCD

Question based on the given segment:

What will be the output of the following program?

#include <stdio.h>

int main() {
  puts("Hello ");
  printf("World");
  puts("!");

  return 0;
}
Hello World!
Hello
World!
Hello World
!
Hello
World
!

Displaying a string on the screen using printf

If you wish to display a string without the newline character at the end, you have two options. We’ve already seen one: just use printf for straightforward strings. But what if the string has percentage signs:

printf("100%");

Here, printf won’t give us the desired output. To ensure our string is displayed as intended, we can use the format specifier %s:

printf("%s", "100%");

Now, printf will print the string exactly as it is. While this solution may not seem elegant, there’s another function we can use.

Using fputs for Display

The fputs function is akin to puts, but it’s meant for file output. However, by passing stdout as the file parameter, we can use it to display strings on the screen:

fputs("AB", stdout);
fputs("CD", stdout);

Output:

ABCD

As you can see, fputs doesn’t append a newline character at the end.

You can substitute any puts call with fputs by passing stdout as the file parameter and adding '\n' at the end of the string you want to display:

fputs("fputs vs puts\n", stdout);
// achieves the same result as
puts("fputs vs puts");
Похожее
vector::size in C++ (With Examples)
In C++, the std::vector container is a dynamic array that can resize itself automatically. A common need is to determine how many elements a vector currently holds. Enter the size function! This article will break down how the size function works, show you some practical examples, and give insights into related features of vectors.
go

Implementing puts

Let’s try to craft our version of the puts function to get a better grasp of its workings:

#include <stdio.h>

int my_puts(const char* s) {
  while (*s != '\0') {
    int result = putchar(*s);
    if (result < 0) {
      return result;
    }

    s++;
  }

  return putchar('\n');
}

int main() {
  my_puts("AB");
  my_puts("CD");

  return 0;
}

Output:

AB
CD

From here, you can adjust the logic as you see fit. You can decide whether to append the '\n' at the end or skip it. It’s all up to you.

Exercises

  1. Using the puts function:

    • Write a C program that uses the puts function to display the phrase “Hello, World!” on the screen.
    • Add a printf function in your program to display the same phrase. Compare the results.
    • Observe how both functions print the text. What’s the difference?
  2. Experimenting with the fputs function:

    • Create a program that uses fputs to display two strings, “Hello” and “World”, on the same line.
    • Then, use puts for the same purpose. Notice the difference in the output.
  3. Writing your version of puts:

    • Attempt to implement your rendition of the puts function, naming it my_puts. Your function should take a string as its argument and print it, adding a newline character at the end.
    • Show off your function by displaying the phrase “This is my take on the puts function!“.

Discussion

© 2024, codelessons.dev