📚

Lecture Notes: User Input in C

Jul 29, 2024

Getting Input from the User in C

Introduction

  • This tutorial focuses on how to gather input from users in C programs.
  • Input can be various types of information such as integers, doubles, characters, and strings.

Prompting the User

  • To get input, we first need to prompt the user. This can be done using printf (print formatted). printf("Enter your age:");

Declaring Variables

  • Before getting input, declare variables to store the data. int age; // Variable for storing age

Getting Input: Using scanf

  • Use scanf to get user input. It's the opposite of printf.

    • Syntax for getting an integer: scanf("%d", &age); // Use & to pass the address of the variable
      • & is used for pointers; it gives the location of the variable.
  • Printing the gathered information:

    printf("You are %d years old.", age);

Example of Integer Input

  • Run the program:
    • Prompt: "Enter your age".
    • If user enters 50, output will be: "You are 50 years old."

Getting Floating Point Input

  • For a double input (e.g., GPA): double GPA; printf("Enter your GPA:"); scanf("%lf", &GPA); // Use %lf for double printf("Your GPA is %lf", GPA);

Getting Character Input

  • To read a single character (e.g., grade): char grade; printf("Enter your grade:"); scanf(" %c", &grade); // Use %c for character printf("Your grade is %c", grade);

Getting String Input

  • To read a string: char name[20]; // Declare a string variable with max length printf("Enter your name:"); scanf("%s", name); // Use %s for string printf("Your name is %s", name);
  • Note: scanf stops at the first space, so only the first word will be captured.

Using fgets for Strings

  • To capture strings with spaces, use fgets: fgets(name, sizeof(name), stdin); // Read a string with spaces
  • **Syntax:
    • First argument: Variable to store the input.
    • Second argument: Maximum number of characters to read.
    • Third argument: Input stream (usually stdin).**

Example of Using fgets

  • Run the program: printf("Enter your name:"); fgets(name, sizeof(name), stdin); printf("Your name is %s", name);
  • This will handle inputs such as "John Smith" correctly.

Considerations with New Lines

  • When using fgets, a newline character may be included in the string. Be aware of how this affects output.

Conclusion

  • Understanding how to get different types of inputs from users is essential in C programming.
  • Experiment with scanf and fgets to become comfortable with user input.