Skip to content

Commit

Permalink
Update scanf.md
Browse files Browse the repository at this point in the history
  • Loading branch information
Sriparno08 authored Jan 23, 2025
1 parent cedc240 commit 50cd0a3
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions content/c/concepts/basic-output/terms/scanf/scanf.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
Title: 'scanf()'
Description: 'Read a user input and assign it to a variable.'
Description: 'Reads a user input and assigns it to a variable.'
Subjects:
- 'Code Foundations'
- 'Computer Science'
Expand All @@ -12,22 +12,24 @@ CatalogContent:
- 'paths/computer-science'
---

The **`scanf()`** ("scan formatted string") function reads a user input, and then converts that input into a value that it assigns to a variable.
The **`scanf()`** (scan formatted string) function reads a user input and then converts that input into a value that it assigns to a variable.

## Syntax

```pseudo
scanf(string, &variable, &variable2, ... &variableN)
scanf(string, &variable, &variable2, ..., &variableN)
```

The `scanf()` function takes a format specifier string as input, along with a variable for each format specifier in the string. The format specifier string acts as a template that the function will use to convert the user input into values for the variables.

For a short list of format specifiers you can use in the input string, see the 'Format Specifiers' table in the [printf()](../printf/printf.md) documentation.
For a short list of format specifiers you can use in the input string, see the 'Format Specifiers' table in the [`printf`](https://www.codecademy.com/resources/docs/c/basic-output/printf) documentation.

> **Note:** `scanf()` does not have any intrinsic validation of the user input. This can cause errors if the user input does not match the format specifiers in the string.
## Examples

In the following example, the format specifier `%d` tells the function to expect an integer, then assigns it to the variable `yourNumber`:

```c
#include <stdio.h>

Expand All @@ -40,7 +42,7 @@ int main(void) {
}
```
The format specifier `%d` tells the function to expect an integer, then assigns it to the variable `yourNumber`. This means that if the user typed in `3`, the output would be:
If the user typed in `3`, the output would be:
```shell
Your favorite number is: 3
Expand All @@ -57,11 +59,12 @@ int main(void) {

printf("Type your favorite number and letter:");
scanf("%d%c", &yourNumber, &yourLetter);
printf("Your favorite number is: %d, and your favorite letter is: %c", yourNumber, yourLetter);
printf("Your favorite number is: %d and your favorite letter is: %c", yourNumber, yourLetter);
}
```
If the user typed in `4B`, the output would be:
```shell
Your favorite number is: 4, and your favorite letter is: B
```
Your favorite number is: 4 and your favorite letter is: B
```

0 comments on commit 50cd0a3

Please sign in to comment.