printf, scanf

In C programming, interacting with the outside world is a core function of any application. The C standard library provides the stdio.h header file to define a series of functions for handling standard input and output, among which the two most common and fundamental are printf and scanf. These two functions form the primary bridge between programs reading user data and displaying results to users; mastering their correct usage is crucial for writing robust C programs.
printf stands for "print formatted string," whose core function is to convert variable values into text based on specified format specifiers and output them to the standard output device (usually the screen). The basic syntax structure of this function is as follows:

int printf(const char *format, ...);

The first parameter format is a string containing formatting instructions. If additional arguments are provided during invocation, they must correspond one-to-one with placeholders in the format specifier. Common format specifiers include %d (signed decimal integer), %f (floating-point number), and %s (string), among others.

To understand this more intuitively, here is a simple example code:

#include <stdio.h>

int main() {
    int age = 25;
    double height = 1.75;
    char *name = "Alice";

    printf("Name: %s\n", name);
    printf("Age: %d years\n", age);
    printf("Height: %.2f meters\n", height); // %.2f indicates rounding to two decimal places

    return 0;
}

Running the above code will output:

Name: Alice
Age: 25 years
Height: 1.75 meters

It is worth noting that printf returns the number of characters actually written (excluding \n). This is very useful when handling file redirection or counting output length. Furthermore, when using %s to output a string, it must be ensured that what is passed is a pointer to the string; one cannot directly pass a string literal as the first argument like scanf does to receive data, but passing a string literal directly in printf is entirely legal because it acts as a constant pointer.

Formatted Input Processing of scanf Function

If printf is responsible for displaying information to the outside world, then scanf is responsible for reading data from standard input devices (usually the keyboard). The full name of scanf is "scan format," which allows programs to parse an input stream according to specific formatting requirements and store the results in specified variables. Its basic syntax is as follows:

int scanf(const char *format, ...);

Similar to printf, scanf also uses format specifiers to define data types and structures. During invocation, pointers to variables must be provided as parameters because the function needs to store parsed values into these memory addresses. Common format specifiers include %d (integer), %f (floating-point number), and %c (character), among others.

Below is a complete interactive example combining printf and scanf:

#include <stdio.h>

int main() {
    int score;
    float price;

    printf("Enter your grade (0-100): ");
    scanf("%d", &score);

    if (score >= 90) {
        printf("Congratulations! You have received an excellent rating!\n");
    } else {
        printf("Keep trying.\n");
    }

    printf("Enter the product price: ");
    scanf("%f", &price);
    printf("Formatted price is: %.2f\n", price);

    return 0;
}

There are several key points to pay special attention to when using scanf. First, you must use the address-of operator & to pass variable addresses; otherwise, the function cannot modify the value of the original variables. Second, input format must be completely consistent with the formats defined in the code. For example, if an integer %d is defined, entering a decimal point (such as 10.5) by the user will cause read failure or undefined behavior. Finally, it is recommended to check return values after reading to ensure that the expected amount of data was successfully read; this is crucial for handling erroneous inputs.

Best Practices and Precautions for Formatted Output

In actual development, merely mastering basic syntax is insufficient; understanding the details of format control can significantly enhance code readability and robustness.

  1. Type Matching: Using incorrect format specifiers leads to undefined behavior. For example, attempting to read a floating-point variable with %d will cause severe logical errors.
  2. String Safety: Although printf can directly output string literals, when processing user-input strings (such as via scanf("%s", buffer)), one must pay close attention to buffer overflow issues; avoid using unsafe functions or impose limits on input lengths accordingly.
  3. Floating-Point Precision: For floating-point number outputs, by default only a small number of decimal places may be displayed, leading to information loss. It is usually recommended to use .2f or higher precision formats to control display effects.
  4. Input Validation: In actual projects, user input should not be blindly trusted. For scanf, return values should always be checked to ensure they match the expected value (usually 1), so that friendly prompts can be given and loops terminated or requests for re-input made when input formats are incorrect.

By mastering printf and scanf, developers can not only build programs capable of fluent interaction with users but also lay a solid foundation for learning advanced topics such as file operations and network programming later on. These two functions are the mandatory path to starting C language, serving as core tools throughout the entire lifecycle of the language.