Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

puts() vs printf() for printing a string

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In C, given a string variable str, which of the following two should be preferred to print it to stdout? 

1) puts(str);
2) printf(str);

puts() can be preferred for printing a string because it is generally less expensive (implementation of puts() is generally simpler than printf()), and if the string has formatting characters like ‘%s’, then printf() would give unexpected results. Also, if str is a user input string, then use of printf() might cause security issues (see this for details). 
Also note that puts() moves the cursor to next line. If you do not want the cursor to be moved to next line, then you can use following variation of puts(). 

fputs(str, stdout)

You can try following programs for testing the above discussed differences between puts() and printf().

Program 1 

C




// C program to show the use of puts
#include <stdio.h>
int main()
{
    puts("Geeksfor");
    puts("Geeks");
 
    getchar();
    return 0;
}


Output

Geeksfor
Geeks

Program 2 

C




// C program to show the use of fputs and getchar
#include <stdio.h>
int main()
{
    fputs("Geeksfor", stdout);
    fputs("Geeks", stdout);
 
    getchar();
    return 0;
}


Output

GeeksforGeeks

Program 3 

C




// C program to show  the side effect of using
// %s in printf
#include <stdio.h>
int main()
{
    // % is intentionally put here to show side effects of
    // using printf(str)
    printf("Geek%sforGeek%s");
    getchar();
    return 0;
}


Output

Geek�����forGeek����

Program 4 

C




// C program to show the use of puts
#include <stdio.h>
int main()
{
    puts("Geek%sforGeek%s");
    getchar();
    return 0;
}


Output

Geek%sforGeek%s

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Last Updated : 14 Apr, 2023
Like Article
Save Article
Similar Reads