scanf
Example of using the scanf() function
#include <stdio.h>
int main()
{
char website[20];
// Do not forget to specify the maximum length in []
// If you do not specify it, the default will be only one character.
// and when you enter a longer message, scanf will return NULL
printf("Type your website name:\n");
scanf("%s", website);
printf("You typed %s \n", website);
return 0;
}
gcc -o scanf scanf.c
./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("%s", website);
Try to change the code now by adding & to the website
scanf("%s", &website);
Nothing has to change.
We'll figure it out.
#include <stdio.h>
int main()
{
char website[20];
int year;
printf("Type your website name:\n");
scanf("%s", website); // do not need to use & because it is an array
printf("Which year it was made:\n");
scanf("%d", &year); // need to use &
printf("You website is %s. It was made in %d \n", website, year);
return 0;
}
Pay attention.
scanf("%d", &year);
In all cases, except for the array, put & mandatory.
If you simply write year, you will get Segmentation fault (core dumped)
during the execution of the program.
Write &year, compile and execute.
gcc -o scanf scanf.c
./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
| C development | |
| Textbook on C | |
| Boolean in C | |
| Sockets in C | |
| K&R | |
| What is argc, char * argv[] | |
| Function scanf() | |
| Pointers | |
| Structures in C | |
| Operator «arrow» pointer to member structure |