C Programming Language Tutorial

Variables and Data Types

Input/Output

Looping and Selection Structures

Array

Functions

Preprocessing Command

Pointer

Structure

File Operations

Important Knowledge

scanf(): Read Data Entered From The Keyboard in C Programming Language

In this tutorial, we'll explore the scanf() function in the C programming language, which is used for reading formatted input from the standard input stream (usually the keyboard). We'll cover the basic syntax, usage, and some examples to demonstrate the function.

Basic Syntax

The scanf() function is defined in the stdio.h library, so make sure to include this header at the beginning of your C program.

#include <stdio.h>

The basic syntax of the scanf() function is as follows:

int scanf(const char *format, ...);
  • format: A string that specifies the expected format of the input. It contains placeholders, known as format specifiers, which indicate the type and size of the data to be read.
  • ...: These are pointers to the memory locations where the read values will be stored.

Format Specifiers

Here are some common format specifiers used in scanf():

  • %d: integer (int)
  • %c: character (char)
  • %s: string (char array)
  • %f: floating-point number (float)
  • %lf: double floating-point number (double)

Basic Usage

To use scanf(), you need to pass the format specifier string and pointers to the variables where the input will be stored.

For example, let's read an integer from the user:

#include <stdio.h>

int main() {
    int num;
    printf("Enter an integer: ");
    scanf("%d", &num);
    printf("You entered: %d\n", num);

    return 0;
}

In this example, %d is the format specifier for an integer, and &num is the pointer to the num variable.

Reading Multiple Values

You can read multiple values with a single scanf() call by including multiple format specifiers in the format string and passing the corresponding pointers.

Here's an example of reading two integers and a character:

#include <stdio.h>

int main() {
    int num1, num2;
    char ch;

    printf("Enter two integers and a character: ");
    scanf("%d %d %c", &num1, &num2, &ch);

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

    return 0;
}

In this example, the format string is "%d %d %c", and we pass the pointers to num1, num2, and ch.

Handling String Input

When using %s to read a string, it's essential to allocate enough space in the character array to hold the input. Also, note that you don't need to use the address-of operator & when passing a character array to scanf().

#include <stdio.h>

int main() {
    char str[100];

    printf("Enter a string: ");
    scanf("%s", str);

    printf("You entered: %s\n", str);

    return 0;
}

Keep in mind that scanf() with %s reads input until the first whitespace character is encountered. To read a full line, consider using fgets() instead.

Conclusion

In this tutorial, we learned about the scanf() function in C, its basic syntax, usage, and some examples. It's a powerful function for reading formatted input from the user, but remember to handle memory allocation and format specifiers correctly to avoid issues.

  1. Reading input from the keyboard with scanf() in C:

    • Description: The scanf() function is used to read input from the keyboard. It takes format specifiers to interpret and store the input.
    • Code:
      #include <stdio.h>
      
      int main() {
          int num;
          printf("Enter an integer: ");
          scanf("%d", &num);
          printf("You entered: %d\n", num);
      
          return 0;
      }
      
  2. Formatting options and specifiers in scanf() function:

    • Description: scanf() uses format specifiers to interpret the input. For example, %d for integers, %f for floats, %c for characters, etc.
    • Code:
      #include <stdio.h>
      
      int main() {
          float floatNum;
          char character;
      
          printf("Enter a float and a character: ");
          scanf("%f %c", &floatNum, &character);
      
          printf("You entered: %.2f and %c\n", floatNum, character);
      
          return 0;
      }
      
  3. Handling different data types with scanf() in C language:

    • Description: scanf() supports different format specifiers for various data types (integers, floats, characters, strings, etc.).
    • Code:
      #include <stdio.h>
      
      int main() {
          int intNum;
          float floatNum;
      
          printf("Enter an integer and a float: ");
          scanf("%d %f", &intNum, &floatNum);
      
          printf("You entered: %d and %.2f\n", intNum, floatNum);
      
          return 0;
      }
      
  4. Input validation and error handling using scanf() in C:

    • Description: Check the return value of scanf() to handle input errors and validate user input.
    • Code:
      #include <stdio.h>
      
      int main() {
          int num;
      
          printf("Enter an integer: ");
          if (scanf("%d", &num) == 1) {
              printf("You entered: %d\n", num);
          } else {
              printf("Invalid input.\n");
          }
      
          return 0;
      }
      
  5. C code examples demonstrating scanf() usage:

    • Code:
      #include <stdio.h>
      
      int main() {
          int age;
          float height;
      
          printf("Enter your age and height: ");
          scanf("%d %f", &age, &height);
      
          printf("You are %d years old and %.2f meters tall.\n", age, height);
      
          return 0;
      }
      
  6. Buffer overflow prevention with scanf() in C programming:

    • Description: Limit the number of characters read by scanf() to prevent buffer overflow.
    • Code:
      #include <stdio.h>
      
      int main() {
          char name[20];
      
          printf("Enter your name (up to 19 characters): ");
          scanf("%19s", name);
      
          printf("Hello, %s!\n", name);
      
          return 0;
      }
      
  7. Combining scanf() with loops for iterative input in C:

    • Description: Use loops to repeatedly prompt the user for input until valid data is provided.
    • Code:
      #include <stdio.h>
      
      int main() {
          int num;
      
          do {
              printf("Enter a positive integer: ");
              if (scanf("%d", &num) == 1 && num > 0) {
                  break;
              } else {
                  printf("Invalid input. Try again.\n");
                  // Clear the input buffer
                  while (getchar() != '\n');
              }
          } while (1);
      
          printf("You entered: %d\n", num);
      
          return 0;
      }
      
  8. Advanced scanf() techniques for complex input scenarios:

    • Description: For more complex scenarios, you may need to mix different format specifiers and handle input intricacies.
    • Code:
      #include <stdio.h>
      
      int main() {
          char name[50];
          int age;
      
          printf("Enter your name and age: ");
          if (scanf("%49s %d", name, &age) == 2) {
              printf("Hello, %s! You are %d years old.\n", name, age);
          } else {
              printf("Invalid input.\n");
          }
      
          return 0;
      }