Read User Input in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to read user input in the C programming language using the scanf() function. The scanf() function is a powerful tool for reading input from users and is defined in the standard input/output library stdio.h. C is a strongly typed language that supports various data types. Throughout this lab, we will focus on using the char and int data types to read and display user input.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/PointersandMemoryGroup(["`Pointers and Memory`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/comments("`Comments`") c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/data_types("`Data Types`") c/BasicsGroup -.-> c/operators("`Operators`") c/CompoundTypesGroup -.-> c/strings("`Strings`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/PointersandMemoryGroup -.-> c/memory_address("`Memory Address`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") subgraph Lab Skills c/output -.-> lab-136075{{"`Read User Input in C`"}} c/comments -.-> lab-136075{{"`Read User Input in C`"}} c/variables -.-> lab-136075{{"`Read User Input in C`"}} c/data_types -.-> lab-136075{{"`Read User Input in C`"}} c/operators -.-> lab-136075{{"`Read User Input in C`"}} c/strings -.-> lab-136075{{"`Read User Input in C`"}} c/user_input -.-> lab-136075{{"`Read User Input in C`"}} c/memory_address -.-> lab-136075{{"`Read User Input in C`"}} c/function_declaration -.-> lab-136075{{"`Read User Input in C`"}} end

Set Up the Development Environment

In this step, we will set up our development environment and create a new C file for our program.

  1. Open a terminal in the WebIDE. You should be in the /home/labex/project directory by default. If you're not sure, you can type pwd (print working directory) to check your current location.

  2. Create a new file named user_input.c using the following command:

    touch user_input.c

    The touch command creates a new, empty file if it doesn't exist, or updates the timestamp of an existing file.

  3. Open the user_input.c file in the WebIDE editor. You can do this by clicking on the file name in the file explorer on the left side of the WebIDE, or by using the Open File option in the File menu.

Write the Basic Program Structure

In this step, we will write the basic structure of our C program.

  1. In the user_input.c file, add the following code:

    #include <stdio.h>
    
    int main() {
        // We will add our code here
        return 0;
    }

    Let's break this down:

    • #include <stdio.h> tells the compiler to include the standard input/output library. This library contains functions like printf() and scanf() that we'll use for input and output.
    • int main() is the main function where our program starts executing. Every C program must have a main function.
    • The curly braces { } define the body of the main function.
    • return 0; at the end of main indicates that the program has executed successfully.
  2. Save the file. You can do this by pressing Ctrl+S or by selecting Save from the File menu.

Implement User Input for Name

Now, let's implement the functionality to read the user's name.

  1. Modify the user_input.c file to include the following code inside the main() function:

    #include <stdio.h>
    
    int main() {
        char name[100];
    
        printf("Enter your name: ");
        scanf("%s", name);
    
        printf("Hello, %s!\n", name);
    
        return 0;
    }

    Here's what each new line does:

    • char name[100]; declares an array of characters (a string) that can hold up to 99 characters plus the null terminator.
    • printf("Enter your name: "); prompts the user to enter their name.
    • scanf("%s", name); reads a string from the user input and stores it in the name array. The %s format specifier is used for reading strings.
    • printf("Hello, %s!\n", name); prints a greeting using the name entered by the user. The %s in the format string is replaced by the value of name.
  2. Save the file.

Add Age Input

Let's extend our program to also ask for the user's age.

  1. Modify the user_input.c file to include age input:

    #include <stdio.h>
    
    int main() {
        char name[100];
        int age;
    
        printf("Enter your name: ");
        scanf("%s", name);
    
        printf("Enter your age: ");
        scanf("%d", &age);
    
        printf("Hello, %s! You are %d years old.\n", name, age);
    
        return 0;
    }

    What's new here:

    • int age; declares an integer variable to store the user's age.
    • We've added another printf() and scanf() pair to prompt for and read the age.
    • scanf("%d", &age); reads an integer from the user input. The %d format specifier is used for integers. Note the & before age - this is because scanf() needs the memory address of the variable to store the input.
    • The final printf() now includes the age in the output message.
  2. Save the file.

Compile and Run the Program

In this final step, we will compile our C program and run it to see the results.

  1. In the terminal, navigate to the directory containing your user_input.c file:

    cd /home/labex/project

    This step ensures you're in the right directory. If you're already there, you'll see a message saying "cd: no such file or directory", which you can ignore.

  2. Compile the program using the GCC compiler:

    gcc user_input.c -o user_input

    This command tells GCC to compile user_input.c and create an executable named user_input. If there are any errors in your code, you'll see error messages here. If that happens, go back to your code, fix the errors, and try compiling again.

  3. Run the compiled program:

    ./user_input

    The ./ tells the shell to look for the program in the current directory.

alt text
  1. The program will prompt you to enter your name and age. Type your responses and press Enter after each input.

  2. You should see a personalized greeting message with your name and age.

If you encounter any issues, double-check your code for typos and make sure you've saved all changes before compiling.

Summary

In this lab, you have learned how to read user input in C using the scanf() function. You created a program that prompts users for their name and age, reads the input, and displays a personalized greeting message. This exercise has introduced you to basic input/output operations in C, working with different data types (char arrays for strings and int for integers), and the process of compiling and running a C program.

Key takeaways:

  1. The scanf() function is used to read input from the user.
  2. Different format specifiers (%s for strings, %d for integers) are used depending on the type of input you're reading.
  3. When reading integers or other non-string types with scanf(), you need to use the & operator to pass the address of the variable.
  4. The compilation process turns your C code into an executable program.

These fundamental skills form the basis for more complex C programming tasks and will be valuable as you continue to learn and develop your programming abilities. Remember, practice is key in programming - try modifying this program or creating new ones to reinforce what you've learned!

Other C Tutorials you may like