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

Related articles
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
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: