Reading input from the terminal in C

In C, you can read input from the terminal or console using the scanf function, which is part of the standard input/output library (stdio.h). scanf allows you to read input values from the user based on format specifiers. Here's a basic overview of how to use scanf to read input in C:


#include 

int main() {
    int age;
    printf("Enter your age: ");
    
    // Use scanf to read an integer from the user
    scanf("%d", &age);
    
    printf("You entered: %d years old\n", age);

    return 0;
}

In the above example:

  • printf is used to prompt the user for input by displaying the message "Enter your age: ".
  • scanf is used to read an integer (%d) from the user. The '&' operator is used to get the memory address of the age variable so that scanf can store the input value there.
  • After reading the input, you can use printf to display the entered value or perform any further processing with it.

When you run this program, it will wait for you to enter an integer, and after you press Enter, it will display the entered value:


Enter your age: 25
You entered: 25 years old

Here are some important points to remember when using scanf for input:

  1. Make sure to use the correct format specifier (%d for integers, %f for floating-point numbers, %c for characters, etc.) that matches the type of input you expect.
  2. Ensure that the memory location provided to scanf using the '&' operator matches the format specifier. For example, if you're reading an integer, provide the address of an integer variable.
  3. scanf can be sensitive to input errors, so it's a good practice to handle potential issues with user input, like checking the return value of scanf to ensure it successfully read the expected number of values.
  4. Be aware that scanf might leave newline characters (\n) in the input buffer, which can cause unexpected behavior. You can handle this by consuming the newline character if needed.

Reading input from the terminal is essential for creating interactive programs that take user input and perform actions based on that input.