C User Input

Introduction

In this chapter, we will learn how to take user input in C programming. Handling user input is a crucial part of many applications, allowing programs to interact dynamically with users. In C, user input is typically handled using standard input functions such as scanf, gets, and fgets.

Basic Input with scanf

The scanf function is used to read formatted input from the standard input (keyboard). It is one of the most commonly used functions for taking user input in C.

Syntax

int scanf(const char *format, ...);
  • format: A string that specifies the format of the input.
  • ...: Additional arguments providing pointers to the variables where the input values should be stored.

Example: Reading an Integer

#include <stdio.h>

int main() {
    int number;

    printf("Enter an integer: ");
    scanf("%d", &number);

    printf("You entered: %d\n", number);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Enter an integer: 42
You entered: 42

Example: Reading Multiple Values

#include <stdio.h>

int main() {
    int num1, num2;

    printf("Enter two integers: ");
    scanf("%d %d", &num1, &num2);

    printf("You entered: %d and %d\n", num1, num2);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Enter two integers: 10 20
You entered: 10 and 20

Reading Strings

Reading strings using scanf requires careful handling to avoid common pitfalls such as buffer overflows. The gets and fgets functions provide safer alternatives for reading strings.

Example: Reading a String with scanf

#include <stdio.h>

int main() {
    char name[50];

    printf("Enter your name: ");
    scanf("%s", name);

    printf("Hello, %s!\n", name);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Enter your name: Alice
Hello, Alice!

Note: scanf reads a single word (until a space is encountered). For reading entire lines, gets or fgets should be used.

Reading a Line of Text with gets

The gets function reads a line of text from the standard input (until a newline character is encountered). However, gets is considered unsafe because it does not perform bounds checking, which can lead to buffer overflows.

Example: Reading a String with gets

#include <stdio.h>

int main() {
    char name[50];

    printf("Enter your name: ");
    gets(name);

    printf("Hello, %s!\n", name);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Enter your name: Alice Johnson
Hello, Alice Johnson!

Warning: Avoid using gets in production code due to its security vulnerabilities. Use fgets instead.

Reading a Line of Text with fgets

The fgets function reads a specified number of characters from the standard input and stores them in a buffer. It is safer than gets because it performs bounds checking.

Syntax

char *fgets(char *str, int n, FILE *stream);
  • str: Pointer to an array where the read string will be stored.
  • n: Maximum number of characters to read (including the null character).
  • stream: Input stream to read from (stdin for standard input).

Example: Reading a String with fgets

#include <stdio.h>

int main() {
    char name[50];

    printf("Enter your name: ");
    fgets(name, sizeof(name), stdin);

    // Remove the trailing newline character, if present
    size_t len = strlen(name);
    if (len > 0 && name[len-1] == '\n') {
        name[len-1] = '\0';
    }

    printf("Hello, %s!\n", name);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Enter your name: Alice Johnson
Hello, Alice Johnson!

Simple C Programs to Demonstrate User Input

Program 1: Adding Two Numbers

Example:

#include <stdio.h>

int main() {
    int num1, num2, sum;

    printf("Enter two integers: ");
    scanf("%d %d", &num1, &num2);

    sum = num1 + num2;

    printf("Sum: %d\n", sum);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Enter two integers: 15 25
Sum: 40

Program 2: Reading and Printing a String

Example:

#include <stdio.h>

int main() {
    char name[50];

    printf("Enter your name: ");
    fgets(name, sizeof(name), stdin);

    // Remove the trailing newline character, if present
    size_t len = strlen(name);
    if (len > 0 && name[len-1] == '\n') {
        name[len-1] = '\0';
    }

    printf("Hello, %s!\n", name);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Enter your name: Bob Smith
Hello, Bob Smith!

Program 3: Calculating the Area of a Circle

Example:

#include <stdio.h>

int main() {
    float radius, area;
    const float PI = 3.14159;

    printf("Enter the radius of the circle: ");
    scanf("%f", &radius);

    area = PI * radius * radius;

    printf("The area of the circle is: %.2f\n", area);

    return 0; // Returning 0 to indicate successful execution
}

Output:

Enter the radius of the circle: 5
The area of the circle is: 78.54

Conclusion

Handling user input is a fundamental part of many C programs, allowing for dynamic interaction with users. By understanding and using the standard input functions such as scanf, gets, and fgets, you can read various types of input from the user. It is important to use safe functions like fgets to avoid potential security vulnerabilities. Mastering user input handling is essential for writing interactive and user-friendly C programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top