Linguagem C - Aula 2.2 - Inserindo dados pelo teclado em C - scanf - entrada de dados (2022)
Table of Contents
Introduction
This tutorial provides a step-by-step guide on how to use the scanf
function in the C programming language for reading input from the keyboard. Understanding how to capture user input is essential for interactive programs and enhances your ability to create dynamic applications.
Step 1: Setting Up Your Environment
Before you can use scanf
, ensure you have a suitable environment to write and run your C code.
- Install a C compiler (e.g., GCC).
- Use a code editor or an Integrated Development Environment (IDE) such as Code::Blocks or Visual Studio Code.
Step 2: Writing Your First Program
Start by creating a simple C program to demonstrate the scanf
function.
- Open your code editor and create a new file named
input_example.c
. - Start with the basic structure of a C program:
#include <stdio.h>
int main() {
// Your code will go here
return 0;
}
Step 3: Using scanf to Capture Input
Now, let's add code to capture user input using scanf
.
- Inside the
main
function, declare a variable to hold the user's input. For example, if you want to capture an integer:
int number;
- Use the
scanf
function to read input from the user:
printf("Enter an integer: ");
scanf("%d", &number);
- The complete code should look like this:
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
printf("You entered: %d\n", number);
return 0;
}
Step 4: Compiling and Running Your Program
To see your program in action, follow these steps:
- Open your terminal or command prompt.
- Navigate to the directory where your
input_example.c
file is located. - Compile your program using the following command:
gcc input_example.c -o input_example
- Run your program:
./input_example
- Enter an integer when prompted. The program should display the integer you entered.
Step 5: Handling Different Data Types
You can use scanf
to read different types of data, such as floats or strings. Here’s how:
- For a float:
float decimal;
printf("Enter a decimal number: ");
scanf("%f", &decimal);
- For a string (character array):
char name[50];
printf("Enter your name: ");
scanf("%s", name);
Conclusion
You've learned how to use the scanf
function in C to capture user input from the keyboard. Key takeaways include:
- Setting up your programming environment.
- Writing a basic C program that uses
scanf
. - Compiling and executing your code.
- Capturing different types of input.
Next, consider practicing by creating programs that handle multiple inputs or perform calculations based on user input. Happy coding!