C++23 Update

We now finally have std::print as a way to use std::format for output directly:

#include <print>
#include <string>

int main() {
    // ...
    std::print("Follow this command: {}", myString);
    // ...
}

This combines the best of both approaches.

Original Answer

It's compiling because printf isn't type safe, since it uses variable arguments in the C sense1. printf has no option for std::string, only a C-style string. Using something else in place of what it expects definitely won't give you the results you want. It's actually undefined behaviour, so anything at all could happen.

The easiest way to fix this, since you're using C++, is printing it normally with std::cout, since std::string supports that through operator overloading:

std::cout << "Follow this command: " << myString;

If, for some reason, you need to extract the C-style string, you can use the c_str() method of std::string to get a const char * that is null-terminated. Using your example:

#include <iostream>
#include <string>
#include <stdio.h>

int main()
{
    using namespace std;

    string myString = "Press ENTER to quit program!";
    cout << "Come up and C++ me some time." << endl;
    printf("Follow this command: %s", myString.c_str()); //note the use of c_str
    cin.get();

    return 0;
}

If you want a function that is like printf, but type safe, look into variadic templates (C++11, supported on all major compilers as of MSVC12). You can find an example of one here. There's nothing I know of implemented like that in the standard library, but there might be in Boost, specifically boost::format.


[1]: This means that you can pass any number of arguments, but the function relies on you to tell it the number and types of those arguments. In the case of printf, that means a string with encoded type information like %d meaning int. If you lie about the type or number, the function has no standard way of knowing, although some compilers have the ability to check and give warnings when you lie.

Answer from Qaz on Stack Overflow
Top answer
1 of 9
342

C++23 Update

We now finally have std::print as a way to use std::format for output directly:

#include <print>
#include <string>

int main() {
    // ...
    std::print("Follow this command: {}", myString);
    // ...
}

This combines the best of both approaches.

Original Answer

It's compiling because printf isn't type safe, since it uses variable arguments in the C sense1. printf has no option for std::string, only a C-style string. Using something else in place of what it expects definitely won't give you the results you want. It's actually undefined behaviour, so anything at all could happen.

The easiest way to fix this, since you're using C++, is printing it normally with std::cout, since std::string supports that through operator overloading:

std::cout << "Follow this command: " << myString;

If, for some reason, you need to extract the C-style string, you can use the c_str() method of std::string to get a const char * that is null-terminated. Using your example:

#include <iostream>
#include <string>
#include <stdio.h>

int main()
{
    using namespace std;

    string myString = "Press ENTER to quit program!";
    cout << "Come up and C++ me some time." << endl;
    printf("Follow this command: %s", myString.c_str()); //note the use of c_str
    cin.get();

    return 0;
}

If you want a function that is like printf, but type safe, look into variadic templates (C++11, supported on all major compilers as of MSVC12). You can find an example of one here. There's nothing I know of implemented like that in the standard library, but there might be in Boost, specifically boost::format.


[1]: This means that you can pass any number of arguments, but the function relies on you to tell it the number and types of those arguments. In the case of printf, that means a string with encoded type information like %d meaning int. If you lie about the type or number, the function has no standard way of knowing, although some compilers have the ability to check and give warnings when you lie.

2 of 9
48

Use myString.c_str() if you want a C-like string (const char*) to use with printf.

🌐
Cplusplus
cplusplus.com › reference › cstdio › printf
Printf
C string that contains the text to be written to stdout. It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested.
Discussions

arrays - Trying to printf a string in C - Stack Overflow
Hi guys I'm really confused with this one, basically what I'm trying to do is take an input and save it in a string array and then print whatever I wrote down in the string array. Instead of printf More on stackoverflow.com
🌐 stackoverflow.com
[deleted by user]
Why is that? Because of output buffering. Use fflush(stdout); after each call to printf. But never do this in real life, as it wil slow down your program quite a lot. Also, let the compiler do the pointer gymnastics. When dealing with an array, treat it as an array. Use name[i] rather than calculating the address yourself. More on reddit.com
🌐 r/C_Programming
21
2
August 1, 2019
Is there a function to printf() n characters in a string?
Not sure, but all format specifiers have width and precision properties. printf("%32.32s\n", s); will print exactly 32 characters of the string s, left-padding with spaces if needed and skipping everything after 32 characters. Could you provide an example of what you need? More on reddit.com
🌐 r/cprogramming
3
3
July 2, 2024
Design: String Interpolation vs printf() with Format Strings (which is better/cleaner?)
I think interpolation is far better. It also saves you from the type safety issues that often plague printf implementations in various ways. Note that if you want to support high quality localisation libraries, you may still need to support printf-like functions, although they don't need to be quite as ergonomic, and can support printing only strings. More on reddit.com
🌐 r/ProgrammingLanguages
55
22
October 6, 2024
🌐
NV5 Geospatial Software
nv5geospatialsoftware.com › docs › Format_Codes_CPrintf.html
C printf-Style Format Codes
View our Documentation Center document now and explore other helpful examples for using IDL, ENVI and other products.
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › c-runtime-library › format-specification-syntax-printf-and-wprintf-functions
Format Specification Syntax: `printf` and `wprintf` Functions | Microsoft Learn
The various printf and wprintf functions take a format string and optional arguments and produce a formatted sequence of characters for output. The format string contains zero or more directives, which are either literal characters for output ...
🌐
IBM
ibm.com › docs › en › i › 7.4.0
printf() — Print Formatted Characters
We cannot provide a description for this page right now
Find elsewhere
🌐
GitHub
gist.github.com › dhoerl › 1701181
std::string using printf style format strings · GitHub
std::string using printf style format strings. GitHub Gist: instantly share code, notes, and snippets.
🌐
cppreference.com
en.cppreference.com › cpp › io › c › fprintf
std::printf, std::fprintf, std::sprintf, std::snprintf - cppreference.com
The format string consists of ordinary byte characters (except %), which are copied unchanged into the output stream, and conversion specifications.
🌐
Wikipedia
en.wikipedia.org › wiki › Printf
printf - Wikipedia
2 weeks ago - As the format string is processed left-to-right, a subsequent value is used for each format specifier found. A format specifier starts with a % character and has one or more following characters that specify how to serialize a value. The standard library provides other, similar functions that form a family of printf...
🌐
W3Schools
w3schools.com › java › ref_output_printf.asp
Java Output printf() Method
The %s character is a placeholder for the string "World": ... Note: You will find more "Try it Yourself" examples at the bottom of this page. The printf() method outputs a formatted string.
🌐
University of Surrey
personalpages.surrey.ac.uk › r.bowden › C › printf.html
Format Codes for printf
June 9, 2023 - int printf(const char *format, ...) int fprintf(FILE *stream, const char *format, ...) int sprintf(char *string, const char *format, ...) The functions return the number of characters written, or a negative value if an error occurred. The format string is of the form ·
🌐
Lenovo
lenovo.com › home
Master Printf for Powerful Formatted Output | Lenovo US
To print a single character with ... %c", letter);`. This outputs the character stored in `letter`. Yes, you can print a string using printf by using the `%s` specifier....
🌐
Polytechnique
lix.polytechnique.fr › ~liberti › public › computing › prog › c › C › FUNCTIONS › format.html
printf format identifiers. - LIX (Polytechnique)
If the string is greater than 8 characters, it will be cropped down to size. Here is a little program that shows an alternative to strncpy. As with the 'width' above, the precision does not have to be hard coded, the * symbol can be used and an integer supplied to give its value. The format identifier describes the expected data. The identifier is the character that ends Here is a list of the format identifers as used in 'printf...
🌐
Embedded Artistry
embeddedartistry.com › home › blog › printf a limited number of characters from a string
printf a Limited Number of Characters from a String - Embedded Artistry
December 15, 2021 - // Only 5 characters printed const char * mystr = "This string is definitely longer than what we want to print."; printf("Here are first 5 chars only: %.5s\n", mystr);
🌐
Baeldung
baeldung.com › home › java › core java › formatting output with printf() in java
Formatting Output with printf() in Java | Baeldung
January 8, 2024 - To break the string into separate lines, we have a %n specifier: ... The %n separator printf() will automatically insert the host system’s native line separator.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › printf-in-c
printf in C - GeeksforGeeks
Explanation: The format specifier %-50s prints the string s left-aligned with a minimum width of 50 characters. The remaining spaces are padded with blanks, followed by printing Geeks.
Published   October 18, 2025
🌐
Warp
warp.dev › terminus by warp › bash › bash printf
Bash printf - Use Cases and Examples | Warp
August 3, 2023 - $ printf "Current Currency Rates\\n" $ printf "%4s: %.2f\\n" "USD" $USD "CNY" $CNY "BZD" $BZD "TWD" $TWD Current Currency Rates USD: 1.00 CNY: 7.19 BZD: 0.55 TWD: 31.70 · When writing scripts, echo is the simplest command to print to the standard output. By default, it adds a new line so that you don’t need to! You can print strings and variables and add options to escape backslashes.
Top answer
1 of 2
5

Instead of using

scanf("[%s\n]", string);

to read a line of text, use fgets.

fgets(string, sizeof(string), stdin);

Also, the line:

printf(string);

will not print the contents of string if string contains anything that can be a format for printf. If string is "abcd %d", then printf will expect an int as the second argument. Instead of that, use:

printf("%s", string);
2 of 2
0

There are multiple problems in the code:

  • scanf("[%s\n]", string) does not do what you expect, it reads a character from standard input that must be a [, then reads a space delimited word and stores it to string, then reads and discards the next byte if it is a newline, then reads and discards the next byte if it is a ]. If any of these steps fails, scanf stops and returns the number of valid conversions (0 if the first byte read is not a [ or 1 if a word could be read after the [)

    So if you type 'sam' and hit Enter at the terminal, the conversion will fail immediately because the first byte is not a [ and scanf will return 0, consuming no characters from the input and leaving string unchanged. Since string has automatic storage (a local variable) and was not initialized, it has indeterminate contents, which will look like garbage characters when you print it.

    If you type a [ followed by more than 99 letters, scanf will attempt to store all of them into the string array and cause a buffer overflow when writing beyond the end of this array, invoking undefined behavior. This is a security flaw that could be exploited. To avoid this problem, always specify the maximum number of characters between the % and the s, and do this also for %[ conversions.

    To read a single word from standard input with scanf, you should have used scanf("%99s", string) and checked the return value for success (must be 1). Yet this approach has some drawbacks:

    • you cannot read an empty word: scanf() will return 0 if you just hit the Enter key without any previous input.
    • the rest of the input line, including the newline is left pending in the standard input buffer, which may cause unexpected behavior for further input.
    • the length must be passed as en explicit number: one cannot use sizeof or an expression for the maximum input length, which is at least 1 less than the destination array length, making the code confusing.

    It is recommended to read a full line of input with fgets() or getline() and parse the line with sscanf or custom code.

  • printf(string) is very risky! It will have undefined behavior if the string contains printf conversion specifications such as %s that will cause it to retrieve arguments that you did not pass. If you type [%sam at the prompt, the program will likely crash with a segmentation fault.

    Always pass a string literal as the format string and turn on extra warnings (eg: -Wall -Wextra -Werror) to let the compiler verify the consistency of the format string and the arguments actually passed to printf. In this particular case, you should use printf("%s\n", string).

Here is a modified version:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char line[100];
    char word[100];
    printf("Please type some input: ");
    if (fgets(line, sizeof line, stdin)) {
        printf("You typed this: %s\n", line);
        if (sscanf(line, "%99s", word) == 1) {
            printf("this is the first word: %s\n", word);
            system("pause");
            return 0;
        } else {
            printf("no word was typed\n");
            system("pause");
            return 1;
        }
    } else {
        printf("invalid or missing input\n");
        system("pause");
        return 1;
    }
}
🌐
PHP
php.net › manual › en › function.printf.php
PHP: printf - Manual
The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.
🌐
W3Schools
w3schools.com › c › c_variables_format.php
C Format Specifiers
C Reference C Keywords C <stdio.h> C <stdlib.h> C <string.h> C <math.h> C <ctype.h> C <time.h> C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Practice Problems C Compiler C Syllabus C Study Plan C Interview Q&A · ❮ Previous Next ❯ · Format specifiers are used together with the printf() function to print variables.