scanf
Example of using the scanf() function
#include <stdio.h>
int main(void)
{
char website[20];
// The 19 in %19s is the maximum number of characters to read.
// Without it scanf writes past the end of the array when the
// input is longer than the array.
printf("Type your website name:\n");
scanf("%19s", website);
printf("You typed %s \n", website);
return 0;
}
gcc -std=c17 -Wall -Wextra -Wpedantic scanf.c -o scanf
./scanf
Type your website name: topbicycle.ru You typed topbicycle.ru
Please note that no additional libraries are required to use scanf.
All I needed was #include <stdio.h>;
Do not forget to specify the size of the array
Do not forget that when you are going to read characters, this should be indicated when calling.
Function with the help of %s
scanf("%19s", website);
Try to change the code now by adding & to the website
scanf("%19s", &website);
Nothing has to change.
We'll figure it out.
#include <stdio.h>
int main(void)
{
char website[20];
int year;
printf("Type your website name:\n");
scanf("%19s", website); // no & here: an array name is already an address
printf("Which year it was made:\n");
scanf("%d", &year); // & is required for an int
printf("You website is %s. It was made in %d \n", website, year);
return 0;
}
Pay attention.
scanf("%d", &year);
For every argument except an array, put & before it.
If you simply write year, scanf receives the value of the variable
instead of its address: the behaviour is undefined and the program
usually ends with Segmentation fault (core dumped).
Write &year, compile and execute.
gcc -std=c17 -Wall -Wextra -Wpedantic scanf.c -o scanf
./scanf
Type your website name: heihei.ru Which year it was made: 2018 You website is heihei.ru. It was made in 2018
scanf() successfully handled both the character array and the number.
Article author: Andrei Olegovich