Reading Input from the Terminal

Reading input from the terminal allows your C programs to interact with users and receive data during runtime. In this section, we'll explore the standard input functions, particularly scanf(), which is commonly used for reading input in C.

The scanf() Function

The scanf() function is part of the standard input/output library in C and is used for reading formatted input. It allows you to receive user input and store it in variables. Here's a basic example:

#include <stdio.h>

int main() {
    int age;

    // Prompt user for input
    printf("Enter your age: ");
    
    // Read integer input from the user
    scanf("%d", &age);

    // Display the entered age
    printf("You entered: %d\n", age);

    return 0;
}

In this example, %d is the format specifier for an integer, and &age represents the memory address of the age variable.

Format Specifiers for scanf()

scanf() supports various format specifiers for different types of input:

  • %d: Integer

  • %f: Float

  • %lf: Double

  • %c: Character

  • %s: String

#include <stdio.h>

int main() {
    int num;
    float salary;
    char grade;
    char name[50];

    // Reading different types of input
    scanf("%d", &num);
    scanf("%f", &salary);
    // Note the space before %c to consume the newline character
    scanf(" %c", &grade);  
    scanf("%s", name);

    // Displaying the entered values
    printf("Number: %d\n", num);
    printf("Salary: %.2f\n", salary);
    printf("Grade: %c\n", grade);
    printf("Name: %s\n", name);

    return 0;
}

Reading Strings with Spaces

Reading strings with spaces using scanf() requires a different approach. The %s specifier stops reading at the first whitespace. Instead, you can use the %[^\n] specifier to read a whole line:

#include <stdio.h>

int main() {
    char sentence[100];

    // Reading a whole line
    printf("Enter a sentence: ");
    scanf(" %[^\n]", sentence);

    // Displaying the entered sentence
    printf("You entered: %s\n", sentence);

    return 0;
}

Handling Multiple Inputs

To read multiple inputs in a single scanf() call, you can use multiple format specifiers separated by spaces:

#include <stdio.h>

int main() {
    int num1, num2;

    // Reading two integers
    printf("Enter two numbers separated by a space: ");
    scanf("%d %d", &num1, &num2);

    // Displaying the entered numbers
    printf("Numbers entered: %d and %d\n", num1, num2);

    return 0;
}

Conclusion

Reading input from the terminal is a crucial aspect of interactive C programming. The scanf() function provides a flexible way to receive user input in various formats. Understanding the appropriate format specifiers and handling input effectively enhances the usability of your C programs.

In the upcoming sections, we'll explore more advanced concepts in C programming. If you have specific questions or areas you'd like to delve into further, feel free to ask. Happy coding!