The %s specifier for strings
What you'll learn: How to use the %s format specifier to display sequences of characters, known as strings, using the printf function.
The mail slot for words
In previous lessons, you learned how to print integers using %d. However, a single number isn't enough when you want to output a name, a greeting, or a line of dialogue. In C, a sequence of characters bundled together is called a string.
Think of the %s specifier as a specific type of mail slot in your printf sentence. The s stands for "string." When the computer sees %s, it knows to stop, look at the list of variables you provided after the comma, and plug in a word or a sentence instead of a number.
Seeing it in action
When you use %s, you are telling C to "read the characters starting from this memory location until you hit the end of the string." In C, strings are always enclosed in double quotation marks (" ").
#include <stdio.h>
int main() {
// We are telling the computer to save a piece of text
char name[] = "Alice";
// %s acts as a placeholder for the string "Alice"
printf("Hello, %s! Welcome to the program.\n", name);
// You can also pass a string directly without a variable
printf("Today's secret word is: %s\n", "Mango");
return 0;
}
Why it matters
The %s specifier is incredibly flexible. Unlike a single character (which uses %c), %s doesn't care if the word is three letters long or thirty. It will keep printing every character in the sequence until it reaches the hidden "null terminator," which is a special marker C uses to signal that a string has finished.
If you accidentally use %d for a string, the computer will try to interpret the text's memory address as a number, resulting in a confusing jumble. Using %s ensures the computer treats the data like human-readable text.
Key takeaway
Use the %s specifier inside printf as a placeholder whenever you want to insert a string of text into your output.